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)