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 Answers. Here you can ask and receive answers from other community members. And if you liked or disliked an answer or thread: react with an up- or downvote Enjoy!
0 votes
Hello,

When I do this in code:

var fake = Isolate.Fake.Instance<MyObj>();
Isolate.WhenCalled(() => fake.HasLoaded).WillReturn(false);

Some code I run later will turn it to true, is there a way to say return false only once? I then want it to return true whenever I check it later. I guess, I need it to return false initially, then use CallOriginal() for all subsequent checks.

Thanks.
asked by (13.2k points)

1 Answer

0 votes
Hi,

It is possible to set several behaviors on the same method. In this case the last behavior set will be the default after the rest were used. For example:
[TestMethod]
[Isolated]
public void TwoConsecutiveCallsToWillReturn()
{
    var fakeProduct = Isolate.Fake.Instance<Product>();

    // Calling WhenCalled once cause the value to be the default return value
    Isolate.WhenCalled(() => fakeProduct.Price).WillReturn(20.0f);

    // this call cause the previous behavior to happen once and this behavior becomes the default returned value 
    Isolate.WhenCalled(() => fakeProduct.Price).WillReturn(15.0f);

    // Calling Price the 1st time return 20
    Assert.AreEqual(20.0f, fakeProduct.Price);

    // fakeProduct.Price will return 15 for the rest of the calls
    Assert.AreEqual(15.0f, fakeProduct.Price);
    Assert.AreEqual(15.0f, fakeProduct.Price);
}


In the case you have described where you want to fake the first call and use the original method after you can set two behaviors, for example:
public class Counter
{
    private int counter = 100;

    public int CountAndIncrement()
    {
        return counter++;
    }
}

[TestMethod]
public void CounterTest()
{
    var instance = Isolate.Fake.Instance<Counter>(Members.CallOriginal);
    Isolate.WhenCalled(()=>instance.CountAndIncrement()).WillReturn(0);
    Isolate.WhenCalled(()=>instance.CountAndIncrement()).CallOriginal();

    Assert.AreEqual(0, instance.CountAndIncrement());
    Assert.AreEqual(100, instance.CountAndIncrement());
    Assert.AreEqual(101, instance.CountAndIncrement());
}


Please note that in this test the Members.CallOriginal is used in the fake creation. If it's omitted then Isolate.WhenCalled(()=>instance.CountAndIncrement()).CallOriginal() will be ignored and the method will always return 0. We're investigating it to see if it's a bug.

Please let me know if it helps.

Best Regards,
Elisha
Typemock Support Team
answered by (12k points)
...