This “question” is a documentation of an odd MSTest behaviour I’ve banged my head against a few times, in the hope that it will be useful to other people that encounter the same problem. Consider the following test:
[TestClass]
public class SomeTest {
private List<int> _list;
[TestInitialize]
public void SetUp() {
DoSomething();
_list = new List<int>();
}
[TestMethod]
public void SomeTestMethod() {
_list.Add(42);
...
}
}
Running it produces a System.NullReferenceException: Object reference not set to an instance of an object. on the _list.Add(42); line. It looks like SetUp(), although it has the correct public void signature and the [TestInitialize] attribute, isn’t invoked. What happened?
In this case, further investigation showed that
DoSomething()was throwing an exception. For reasons I cannot comprehend, MSTest (at least when invoked from Visual Studio with ReSharper) swallows exceptions thrown by the[TestInitialize]method and continues with the test method anyway without failing the test.(If anyone can explain the rationale for this behaviour or how it can be turned off, I’d be grateful.)