Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MS Unit Test with pre and post conditions

I have been searching through the internet and documentation but cannot find if MS Unit testing can have a pre and post conditions around a unit test, does anyone know if this can be done?

I am using .net 4.5 and vs 2012.

EXAMPLE in Junit you can have a @before and @after that will run before each unit test and after each unit test, I am looking for the same idea.

like image 361
user101010101 Avatar asked Feb 20 '23 20:02

user101010101


2 Answers

Have a look at Spec#; that allows you to 'declare' pre/post conditions.

Edit Oh, I might have understood the question wrong. I think you need to have a look at [TestInitialize] and [TestCleanup]

like image 118
RobIII Avatar answered Mar 05 '23 04:03

RobIII


Check the Remarks and Examples at this MSDN link that explains all assembly level, class level, and test method(the one you are looking for) explained nicely.

http://msdn.microsoft.com/en-us/library/microsoft.visualstudio.testtools.unittesting.testinitializeattribute%28v=vs.80%29.aspx

In short, following example comes from the above link:

using Microsoft.VisualStudio.TestTools.UnitTesting;
using SampleClassLib;
using System;
using System.IO;
using System.Windows.Forms;

namespace TestNamespace
{
   [TestClass()]
   public class DivideClassTest
   {
      [AssemblyInitialize()]
      public static void AssemblyInit(TestContext context)
      {
         MessageBox.Show("Assembly Init");
         }

      [ClassInitialize()]
      public static void ClassInit(TestContext context)
      {
         MessageBox.Show("ClassInit");
      }

      [TestInitialize()]
      public void Initialize()
      {
         MessageBox.Show("TestMethodInit");
      }

      [TestCleanup()]
      public void Cleanup()
      {
         MessageBox.Show("TestMethodCleanup");
      }

      [ClassCleanup()]
      public static void ClassCleanup()
      {
         MessageBox.Show("ClassCleanup");
      }

      [AssemblyCleanup()]
      public static void AssemblyCleanup()
      {
         MessageBox.Show("AssemblyCleanup");
      }

      [TestMethod()]
      [ExpectedException(typeof(System.DivideByZeroException))]
      public void DivideMethodTest()
      {
         DivideClass target = new DivideClass();
         int a = 0; 
         int actual;
         actual = target.DivideMethod(a);
      }
   }
}
like image 24
Sujeewa Avatar answered Mar 05 '23 03:03

Sujeewa