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
I have a configuration object, and I do not want the configuration to save itself during my unit test. However, I would still like to use the object rather than mocking it. So I have the following code:
[ClassInitialize]
public static void MyClassInitialize(TestContext testContext) 
{
    clsConfiguration configuration = clsConfiguration.Instance;
    Isolate.WhenCalled(() => configuration.Save()).WillReturn(true);
}

However, it only seems to affect the first call. I changed it to this to confirm it:

[ClassInitialize]
public static void MyClassInitialize(TestContext testContext) 
{
    clsConfiguration configuration = clsConfiguration.Instance;
    Isolate.WhenCalled(() => configuration.Save()).DoInstead(
        (context) => { return true; }
    );
}

And I placed a breakpoint on the "return true" and in the actual Save() method. I was able to confirm that the first call goes to the DoInstead, but subsequent calls go to the real configuration object.

If I move the Isolate.WhenCalled to the [TestInitialize] instead of [ClassInitialize] then the problem goes away.

Why I need to call Isolate.WhenCalled for each unit test, instead of just once? All the unit tests share the same instance of the configuration object. Does the WhenCalled get lost between unit tests? Is that because I have [Isolated] on each test? Should I remove that? (I'm a bit unclear on when I should be using it)
asked by MobyDisk (3.6k points)

1 Answer

0 votes
Hi,

You're half way to the exact answer. The behaviors and expectations are being reset between tests. Isolated attribute signals Isolator to reset the behavior and expectations between tests.

In your case, the behavior is set before the first test and right after it the behavior is removed. It is not recommended to remove the Isolated attribute since it'll keep behaviors that were set in other tests.

The simplest solution is using TestInitialize, this way the behavior will be set as expected for every test.

Please let me know if it helps.

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