chevron-thin-right chevron-thin-left brand cancel-circle search youtube-icon google-plus-icon linkedin-icon facebook-icon twitter-icon toolbox download check linkedin phone twitter-old google-plus facebook profile-male chat calendar profile-male
Welcome to Typemock Community! Here you can ask and receive answers from other community members. If you liked or disliked an answer or thread: react with an up- or downvote.
0 votes
Hi
Looking at the documentation:
http://docs.typemock.com/isolator/Default.aspx##Ref.chm/Documentation/FakingDependenciesAAA.html
I want to make sure I understand correctly because it doesn't work.

Let's say I have a class Person which has a dependency to Logger.
Will using this syntax cause a generation of a new Person() and its property Logger to contain a mock of a Logger?

in code: is this initialization:
var person = Isolate.Fake.Dependencies<Person>();


exactly like:
var person = new Person();
var fakeLogger = Isolate.Fake.Instance<ILogger>();
Isolate.WhenCalled(() => person.Logger).WillReturn(fakeLogger);



using Fake.Dependencies gives me a Person but its Logger is null.

Thanks!
asked by nirsh (9.1k points)

2 Answers

0 votes
Hi,

var person = Isolate.Fake.Dependencies<Person>();
uses the constructor of class Person with the most parameters, creates a fake for each parameter and passes them to the constructor.

This is actually equivalent to:
public class Person
{
    public Logger Logger { get; set; }

    public Person(Logger logger)
    {
        this.Logger = logger;
    }
}

[TestMethod]
public void TestMethod1()
{
    var fakeLogger = Isolate.Fake.Instance<Logger>();
    var person = new Person(fakeLogger);
}


There are more things you can do with this API, for instance if you want to pass some real preset arguments and fake the rest you can:
[TestClass]
public class UnitTest1
{
    [TestMethod]
    public void TestMethod1()
    {
        var logger = new Logger();
        var person = Isolate.Fake.Dependencies<Person>(logger);
        person.Logger.PrintLog("this works");
    }
}

public class Logger
{
    public void PrintLog(string str)
    {
        Console.WriteLine(str);
    }
}

public class Dependency
{
    //logic that is not relevant for the test
}

public class Person
{
    public Logger Logger { get; set; }

    public Person(Logger logger)
    {
        this.Logger = logger;
    }

    public Person(Logger logger, Dependency dep)
    {
        this.Logger = logger;
    }
}
In this example person has a real logger object but the Dependency class is faked for you.

You can also obtain the reference to the fake Dependency object from person if you want to set some behavior on it by using:
var fakeDependency = Isolate.GetFake<Dependency>(person);


Hope it helps.
answered by alex (18k points)
0 votes
Hi Alex,
Thanks, it helps - the unclarity was about the dependencies having to be parameters in the constructor.
Nir
answered by nirsh (9.1k points)
...