Using NUnit for Microsoft .Net
Introduction to Unit Testing using NUnit
In this post we will be discuss about the following
What is
Unit Testing?
Advantages
Disadvantages
Introduction
to nUnit
Demo
Ncover
Resources
What is Unit Testing
Unit testing is a method/process by which individual units of source code of the software programs are being tested,a unit as the smallest testable part of an application. In procedural programming a unit could be an entire module but is more commonly an individual function or procedure. In object-oriented programming a unit is often an entire interface, such as a class, but could be an individual method.
This helps the developers to modify the source code without immediate concerns about how such changes might affect the functioning of other units or the program as a whole. Once all of the units in a program have been found to be working in the most efficient and error-free manner possible, larger components of the program can be evaluated by means of integration testing.
Advantages
The goal of unit testing is to isolate each part of the program and show that the individual parts are correct. Unit testing provides a strict, written contract that the piece of code must satisfy. As a result, it affords several benefits.
Unit testing allows the programmer to re-factor code at a later date, and make sure the module still works correctly (i.e. regression testing). This provides the benefit of encouraging programmers to make changes to the code since it is easy for the programmer to check if the piece is still working properly.
Because some classes may have references to other classes, testing a class can frequently spill over into testing another class. A common example of this is classes that depend on a database: in order to test the class, the tester often writes code that interacts with the database. This is a mistake, because a unit test should never go outside of its own class boundary. As a result, the software developer abstracts an interface around the database connection, and then implements that interface with their own mock object. This results in loosely coupled code, minimizing dependencies in the system
Disadvantages
Unit-testing will not catch every error in the program. By definition, it only tests the functionality of the units themselves. Therefore, it will not catch integration errors, performance problems and any other system-wide issues. In addition, it may not be easy to anticipate all special cases of input the program unit under study may receive in reality. Unit testing is only effective if it is used in conjunction with other software testing activities.
It is unrealistic to test all possible input combinations for any non-trivial piece of software. A unit test can only show the presence of errors; it cannot show the absence of errors.
Introduction to nUnit
NUnit is a unit-testing framework for all .Net languages. Initially ported from JUnit
Current Version:Production release, version 2.6,It is being build/designed based unit testing tool for Microsoft .NET. It is written entirely in C# Language and has been completely redesigned to take advantage of many .NET language features,
for example custom attributes and other reflection related capabilities. NUnit brings xUnit to all .NET languages
Download and Current Versions
Start Unit Testing
Nunit has both GUI and console interfaces
NUnit Tutorial:http://www.nunit.org/
NUnit Guide: http://www.nunit.org/index.php?p=documentation
Method Call Coverage
All public methods must be called at least once
Indirect calls allowed
Assertions:
Use AssertEquals(string, object, object) method
Consider use of Random class
Check boundary conditions and failure scenarios (forced-error tests)
Assertions
Assertions are central to unit testing in any of the nUnit frameworks, and NUnit is no exception. NUnit provides a rich set of assertions as static methods of the Assert class. If an assertion fails, the method call does not return and an error is reported to developer. If a test contains more than one assertions, any that follow the one that failed will not be executed. This is the reason, it's usually best to try for one assertion per test. Each method may be called without a message, with a simple text message or with a message and arguments. In the last case the message is formatted using the provided text and arguments.The Assert class provides the most commonly used assertions.
It provides For convenience of presentation, we group Assert methods as follows:
- Equality Asserts
- Identity Asserts
- Comparison Asserts
- Type Asserts
- Condition tests
- Utility methods
Equality Asserts
These methods test whether the two arguments are equal. Overloaded methods are provided for common value types so that languages that don't automatically box values can use them directly.
Assert.AreEqual( int expected, int actual );
Assert.AreEqual( int expected, int actual, string message );
Assert.AreEqual( int expected, int actual, string message,
params object[] parms );
Identity Asserts
Assert.AreSame and Assert.AreNotSame test whether the same objects are referenced by the two arguments.
Assert.AreSame( object expected, object actual );
Assert.AreSame( object expected, object actual, string message );
Assert.AreSame( object expected, object actual, string message,
params object[] parms );
Contains
Assert.Contains is used to test whether an object is contained in an array or list.
Assert.Contains( object anObject, IList collection );
Assert.Contains( object anObject, IList collection, string message );
Condition Tests
Methods that test a specific condition are named for the condition they test and take the value tested as their first argument and, optionally a message as the second. The following methods are provided:
Assert.IsTrue( bool condition );
Assert.IsTrue( bool condition, string message );
Assert.IsTrue( bool condition, string message, object[] parms );
Utility Methods
Two utility methods, Fail() and Ignore() are provided in order to allow more direct control of the test process:
Assert.Fail();
Assert.Fail( string message );
Assert.Fail( string message, object[] parms );
Constraint-Based Assert Model
Assert.That
The constraint-based Assert model uses a single method of the Assert class for all assertions. The logic necessary to carry out each assertion is embedded in the constraint object passed as the second parameter to that method.
Here's a very simple assert using the constraint model:
Assert.That( myString, Is.EqualTo("Hello") );
Sample Code:
using NUnit;
using NUnit.Framework;
using Rhino.Mocks;
using UniversityEmployeeInformation.UniversityEmployeeRepository;
namespace UniversityEmployeeRepositoryTest
{
[TestFixture, System.ComponentModel.Description("UniversityEmployeeRepository Test")]
public class UniversityEmployeeTest
{
private IUniversityEmployeeRep _employee;
[TestFixtureTearDown]
public void TestFixtureTearDown()
{
}
[SetUp]
public void Initialize()
{
_employee = new UniversityEmployeeRep();
}
[Test]
public void GetEmployee()
{
EmployeeFilter employeeFilter = new EmployeeFilter();
employeeFilter.EmployeeId = 1234;
List<UniversityEmployeeDo> employees=_employee.GetEmployees(employeeFilter);
Assert.IsNotNull(employees);
}
}
}
using NUnit;
using NUnit.Framework;
using Rhino.Mocks;
using UniversityEmployeeInformation.UniversityEmployeeRepository;
namespace UniversityEmployeeRepositoryTest
{
[TestFixture, System.ComponentModel.Description("UniversityEmployeeRepository Test")]
public class UniversityEmployeeTest
{
private IUniversityEmployeeRep _employee;
[TestFixtureTearDown]
public void TestFixtureTearDown()
{
}
[SetUp]
public void Initialize()
{
_employee = new UniversityEmployeeRep();
}
[Test]
public void GetEmployee()
{
EmployeeFilter employeeFilter = new EmployeeFilter();
employeeFilter.EmployeeId = 1234;
List<UniversityEmployeeDo> employees=_employee.GetEmployees(employeeFilter);
Assert.IsNotNull(employees);
}
}
}
This sample code demonstrate the unit testing with Nunit
Create a class UniversityEmployeeTest specify the description of testing class by using the attribute
TestFixture,this class has two method which is initializing and shutdown of test case when it is run
1. [SetUp]
public void Initialize()
{
_employee = new UniversityEmployeeRep();
}
In the above method we can initialize the object and creation
2.[TestFixtureTearDown]
public void TestFixtureTearDown()
{
}
In the above method we can specify the method to closed the object when the test is executed
3. public void GetEmployee() is the method where it is mentioned [Test] which we informing the nunit framework that ,this is the method need to test.
In the "GetEmployee()" test case we are just testing the GetEmployees method from Employee class this method returns the list of employees based on the employee filter is passed to "GetEmployees" method.
Since this is a simple test case we just verifying with Assert " Assert.IsNotNull" which returns true if the records exist and it will return false if there is no record exists.
Resources
[1] NUnit - Documentation. Retrieved March 28, 2005, from http://nunit.org/documentation.html
[2] George, Boby and Laurie Williams. An Initial Investigation of Test Driven Development in Industry. Retrieved March 30, 2005, from http://collaboration.csc.ncsu.edu/laurie/Papers/TDDpaperv8.pdf
[3] Ganssle, Jack. XP Deconstructed. Dec 10, 2003. http://www.embedded.com/showArticle.jhtml?articleID=16700086
[4] Provost, Peter. Test Driven Development in .NET. http://www.codeproject.com/dotnet/tdd_in_dotnet.asp
[5] Introduction to Test Drive Development (TDD). Retreived April 1, 2005, from http://www.agiledata.org/essays/tdd.html
[6] Mugridge, Rick. Test Driven Development and the Scientific Method. http://www.agiledevelopmentconference.com/2003/files/P6Paper.pdf
No comments:
Post a Comment