An Introduction to NUnit Framework

Most unit tests are writing by following a very simple pattern as follows:
+. Perform some activity to set up your test.
+. Execute your test.
+. Verify its result.
+. If necessary, reset your environment.

Test methods must reside into a class. This class is known as TestFixture class. In order to make a class as TestFixture class we’ll add [TestFixture] attribute immediate before of the class name declaration as follows:

[TestFixture] 								//indicate the class is a Test Class
public class TestExample
{
		//Methods here
}

Inside the TestFixture class we’ll have test methods. To make a class as Test class we’ll add [Test] attribute immediate before the declaration of the method name as follows:

[TestFixture] 								//indicate the class is a Test Class
public class TestExample
{
	[Test] 										// indicate the method is a Test method
	public void TestMethod()
	{
	
	}
}

Sometimes in order to run tests some setup are needed such as populating dataset, instantiating classes, setting up an environment variable. In such case we’ll need Setup attribute to define a method that will execute before test runs as follows:

[TestFixture] 								//indicate the class is a Test Class
public class TestExample
{
	
	private string _testMessage;
	
	[SetUp] 										//indicate that the method is a setup which will execute before run Test
	public void SetupForTest()
	{
		_testMessage = “This is a test.”;
	}


	[Test] 											//indicate the method is a Test method
	public void TestMethod()
	{
		Debug.WriteLine(_testMessage);
	}
}

In above example the variable _testMessage is initialized inside the SetupForTest method. When TestMethod executes, the value that was assigned to the variable testMessage i.e. “ This is a test.” is written to the Debug console.

Setup code uses to setup our resources before tests. We also need to reset our resources after performing test. To do that NUnit provides TearDown attribute as follows:

[TestFixture] 							//indicate the class is a Test Class
public class TestExample
{
	
	private string _testMessage;
	
	[SetUp] 									//indicate that the method is a setup which will execute before run Test
	public void SetupForTest()
	{
		_testMessage = “This is a test.”;
	}


	[Test] 										//indicate the method is a Test method
	public void TestMethod()
	{
		Debug.WriteLine(_testMessage);
	}

	[TearDown] 								//Reset the value of _testMessage after perform the test
	public void TearDownAfterTest()
	{
		_testMessage = string.Empty;
	}
}

This example replicates a situation in which you may need to reset a resource after a test has finished running. You probably won’t need to reset an instance variable, but you might need to reset an environment variable or roll back a database transaction.

We already executed our tests but it doesn’t test anything. We can change that by using an assert. By using assert we can tell the final result of test to the test runner application. For example we’ll check whether the length of _testMessage>0 then the Test will pass otherwise it will fail as follows:

[Test]
public void MessageLengthGreaterThanZero()
{
	if (_testMessage.Length > 0)
	{
		Assert.Pass();
	}
	else
	{
		Assert.Fail();
	}
} 

In above example NUnit assert will verify that the length of _testMessage is greater than 0. If the length is greater than 0 then we called Assert.Pass() method so that the test is passed otherwise we called the Assert.Fail() method so that fail the test.

Let’s see another example where we’ll see how Assert.Fail() work. In following example we checked if the length of _ testMessage is less than 100 then the test will fail otherwise the test will pass.

[Test]
public void MessageLengthGreaterThan100()
{
	if (_testMessage.Length > 100)
	{
		Assert.Pass();
	}
	else
	{
		Assert.Fail();
	}
}

Different types of asserts available in NUnit test conditions such as

+. Assert.Pass():

The Assert.Pass method immediately ends the test, indicating that it as successful.

+. Assert.Fail():
The Assert. Fail method immediately ends the test, indicating that it has failed.

+. Assert.AreEqual(expected, actual):
The Assert.AreEqual method checks the equality between expected and actual. In that case both actual and equal will be of same type. This is an overloaded method so that it can take any type of value for expected and actual.
@. If we pass different types of numeric value it will works because this method can up-cast or down-cast as needed. For example- passing an integer and a double for expected and actual will not cause any error.
@. For value types assert will verify that expected and actual parameters have the same value.
@. For reference type (an object) asserts will use “the result of objects Equals method” to determine that the assert is succeeds.
Assert.AreNotEqual() method is oppose to Assert.AreEqual() method i.e. it verifies that two values are not equal.

+. Assert.AreSame(expected, actual):

This assert takes reference types i.e. objects as its arguments. Determines whether the expected and actual arguments are the same object i.e. both object occupy same space in memory and not the copies of one another. Asset.AreNotSame() method is oppose to Assert.AreSame() method where check actual and expected are not the same object.

+. Assert.IsTrue(bool) / Assert.IsFalse(bool):

This assert takes either a Boolean variable or a logical condition that can be evaluated to a Boolean result.

+. Assert.IsNull(object) / Assert.IsNotNull(object):

This assert takes a reference type i.e. an object as argument and determine whether it is null.

+. Assert.Greater(x,y) / Assert.GreaterOrEqual(x,y):

Evaluates either two value types or two reference types that implement the IComparable interface to determine if x is greater that y (x > y) or if x is greater than or equal to y (x > = y). Like AreEqual , Greater / GreaterOrEqual can take two different types of numbers, provided it was up – cast/ down – cast appropriately to make the comparison. NUnit also provides Assert.Less and Assert.LessOrEqual which behave in the same way, but verify that x is less than y (x < y) or that x is less than or equal to y (x < = y). Above listed asserts are most commonly used in NUnit. There are many more asserts are available in NUnit library. One can check them from here.

Md. Mojammel Haque
Currently working as Lead Team (Application Architecture) at Raven Systems Ltd.

Passion for software development especially agile practices such as TDD & BDD with in depth knowledge of OOP, DDD, CQRS, ES, GoF, SOLID and PoEAA.

Over 6 years of software development experience ASP.NET. Has the ability to understand and transform complex business requirements into software ensuring applications are delivered on time.

Also experience in non Microsoft .NET technologies such as Dapper.Net, Subversion, Structure Map & AngularJs.

339 Total Views 1 Views Today
Others types of Tests
Mocking the objects

Leave a Comment

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>