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.
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]
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);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With