Under NUnit 2.2.7, .NET 1.1...
I have a class that has a logging service that gets initialized during its static construction phase and used during the instance constructor, something like this:
public class Foo{
private static LogService logSvc = LogServiceFactory.GetLogService();
public Foo(){
logSvc.Debug("Class constructor running.");
}
}
In some tests I want to make sure that I can get to the class without running the static constructor so I don't get all hung up on the log service. So I create a mock:
Foo obj = (Foo)RecorderManager.CreateMockedObject(typeof(Foo));
That works really well... until other fixtures run that actually need to create the object:
Foo obj = new Foo();
When this happens, I get a null reference exception in the object's constructor because the static constructor never gets run.
Thinking out loud, I suppose one possible solution would be to not mock the static constructor and instead mock the LogServiceFactory return value... wouldn't it? But then wouldn't that mean the mock return value has to stick around for later? Hmmm... maybe that wouldn't work.
Anyway, this is a real difficult thing to debug - when you're running a body of several hundred (or several thousand) unit tests, many of which use mocking, and seeing tests for the Foo object fail... then when you ONLY run the Foo object tests, they succeed. It's tough to know where to even start on something like that.
I was lucky and it turned out that I found the few unit tests mocking the Foo static constructor and was able to successfully allow the static constructor to run unmocked, solving the issue. I'd have been hosed if I couldn't do that. It might be something to consider addressing for the future, though I don't know if I have any suggestions - what if you have tests run that need to mock the static constructor... then some that want it to have run... then some more that need it to have been mocked? That doesn't work, either.
This may also be a unit test framework shortcoming - if every test ran in its own AppDomain, wouldn't the whole issue become moot?