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, Try to put all the setup for the test in the test.
  // If necessary add private Setup/Initialise/Teardown methods to assist this 
  // rather than using the one listed above
  [Test]
  public void SomeTest()
  {
  }
 
  // You can add test parameters to a test and use it to test multiple cases 
  [Test]
  [TestCase(5.0d, 0.0d, 3.0d)]
  [TestCase(5.0d, 1.0d, 3.0d)]
  [TestCase(5.0d, 0.0d, 5.0d)]
  public void SomeTest(   double fullLengthSecs, double startTimeSecs, int expectedValue)
  {
  }
}

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: