NUnit - Simple attribute based Unit Testing in .NET
NUnit is a open-source unit-testing framework for all .Net languages.
NUnit has two different ways to run your tests :-
- The console runner, nunit-console.exe, is the fastest to launch, but is not interactive.
- The gui runner, nunit-gui.exe, is a Windows Forms application that allows you to work selectively with your tests and provides graphical feedback.
Sample:-
Here's the way to write a test for a class (Account) - AccountTest. The first method test is TransferFunds.
namespace bankThe first thing to notice about this class is that it has a [TestFixture] attribute associated with it – this is the way to indicate that the class contains test code (this attribute can be inherited). The class has to be public and there are no restrictions on its superclass. The class also has to have a default constructor.
{
using NUnit.Framework;
[TestFixture]
public class AccountTest
{
[Test]
public void TransferFunds()
{
Account source = new Account();
source.Deposit(200.00F);
Account destination = new Account();
destination.Deposit(150.00F);
source.TransferFunds(destination, 100.00F);
Assert.AreEqual(250.00F, destination.Balance);
Assert.AreEqual(100.00F, source.Balance);
}
}
}
The only method in the class – TransferFunds, has a [Test] attribute associated with it – this is an indication that it is a test method. Test methods have to return void and take no parameters. The Assert class defines a collection of methods used to check the post-conditions.
Compile and run this example. Assume that you have compiled your test code into a bank.dll. Start the NUnit Gui (the installer will have created a shortcut on your desktop and in the “Program Files” folder), after the GUI starts, select the File->Open menu item, navigate to the location of your bank.dll and select it in the “Open” dialog box. When the bank.dll is loaded you will see a test tree structure in the left panel and a collection of status panels on the right. Click the Run button, the status bar and the TransferFunds node in the test tree turn red – our test has failed.
There are other useful attributes like [Setup], [ExpectedException(typeof(InvalidOperationException))], and [Ignore("Ignore a fixture")]
More Reading on .NET code testing with NUnit at http://www.nunit.org/getStarted.html
Thanks to the authors for the above material from SourceForge/NUnit.
No comments:
Post a Comment