31

I've used NUnit with VS2008, and now am adapting to MSTest on VS2010. I used to be able to create an object in TestSetup() and dispose of it in TestCleanup(), and have the object created each time a test method was run in NUnit, preventing me from duplicating the code in each test method.

Is this not possible with MSTest? The examples I am finding using the ClassInitialize and ClassCleanup and TestInitialize and TestCleanup attributes only show how to write to the console. None show any more detailed use of these attributes.

Jennifer S
  • 1,419
  • 1
  • 24
  • 43

1 Answers1

49

Here is a simple example using TestInitialize and TestCleanup.

[TestClass]
public class UnitTest1
{
    private NorthwindEntities context;

    [TestInitialize]
    public void TestInitialize()
    {
        this.context = new NorthwindEntities();
    }

    [TestMethod]
    public void TestMethod1()
    {
        Assert.AreEqual(92, this.context.Customers.Count());
    }

    [TestCleanup]
    public void TestCleanup()
    {
        this.context.Dispose();
    }
}
Tom Brothers
  • 5,929
  • 1
  • 20
  • 17
  • Thanks, Tom. Am I correct in assuming that NorthwindEntities is a referenced assembly in the test project? – Jennifer S Jan 07 '11 at 19:18
  • Yes, it was in a referenced assembly. – Tom Brothers Jan 07 '11 at 20:57
  • 7
    Note that TestInitialize and TestCleanup methods must be marked as **public**, as shown. – mungflesh Feb 11 '15 at 14:44
  • Also note: if TestInitialize throws an exception then TestCleanup is *not* called. So while the code above is correct, adding any code after creating the context that could throw will necessitate a `try { ... } catch { TestCleanUp(); throw; }` block. – TamaMcGlinn Jul 29 '20 at 07:10