January 13, 2006

Using NUnit

Running NUnit on the command line

Run a text fixture using the GUI:
"C:\Program Files\NUnit 2.2\bin\nunit-gui.exe" /fixture:sometests.test.mytest /run

Run a text fixture using the Console:
"C:\Program Files\NUnit 2.2\bin\nunit-console.exe" C:\src\ssg\SrcUnitTests\bin\Debug\NUnitTests.dll /fixture :sometests.test.mytest /out:TestResult.txt /exclude:Manual /thread
This will exclude all tests or test fixtures marked as [Category("Manual")], output goes to Results.txt and /thread causes a separate thread to be created for running the tests.

Description of the NUnit test class attributes can be found here
Here is a NUnit skeleton class with the main attributes:
using NUnit.Framework;

[TestFixture]
public class SomeTester
{
 #region Setup/TearDown

 // This is invoked before each [TestFixture]
 // ie once only, before any tests are invoked
 [TestFixtureSetUp] 
 public void TestFixtureSetUp()
 {
 }

 // This is invoked after each [TestFixture]
 // ie once only, after all tests have been invoked
 [TestFixtureTearDown] 
 public void TestFixtureTearDown()
 {
 }

 // This is invoked before each [Test}
 [SetUp] 
 public void Setup()
 {
 }

 // This is invoked after each [Test}
 [TearDown] 
 public void TearDown()
 {
 }

 #endregion Setup/TearDown

 // Format of a Test method
 [Test]
 public void SomeTest()
 {
 }
}
Use these logging lines to generically log the beginning and end of a test using reflection
[Test]
public void SomeTest()
{
 log.Info("*** Beginning Test - " + System.Reflection.
MethodBase.GetCurrentMethod().ToString());
 log.Info("*** Ending Test - " + System.Reflection.
MethodBase.GetCurrentMethod().ToString());
}
alternatively use:
//Output test class and method name:
Debug.WriteLine("*** Beginning Test - " +
  System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.ToString()
  + "." +
  System.Reflection.MethodBase.GetCurrentMethod().Name.ToString());
NUnit Exceptions Use the 'ExpectedException' attribute when the test is expected to result in an exception being thrown.
[Test]
[ExpectedException(typeof(System.Net.Sockets.SocketException))]
public void TestNoServer()
{
...
alternatively use can use the Assert.Throws() method:
Assert.Throws(typeof(System.Net.Sockets.SocketException),
  delegate
  {
     SomeMethodThatShouldThrowAnException();
  });

No comments: