Today's guide is going to be very quick and simple. The actual writing of the unit test is usually pretty easy, the harder part is knowing how to write testable code, setting up/mocking the set dependencies required for your tests and also wrapping third-party code in order to make it testable. In this guide, I'm going to cover all the code you'll need to write to start using NUnit.
First, you'll need to add NUnit to your project, as always this is done via Nuget, either through the package manager console, or the Gui, right click on your visual studio solution -> Manage Nuget packages...
After you have NUnit installed, my advice would be to create a unit test project for each class library you have in your solution. If you have a project called, 'website.core', then I'd have a matching website.core.tests', you should always separate your unit test code from your production code. You never want to deploy your unit tests to your production server. my second bit of advice is that your test library should follow the same folder structure as your class library. If you have a folder called 'repositories' in your class library, create one in your test library. This class goes for your classes, for each class you want to test, you should have a correspnding test class.
Next up is the code. This is the simple bit:
public class When_I_Instantiate_MyClass_
private Mock mockContentRepository;
public void Setup()
mockContentRepository = new Mock();
public void MyTest()
var result = new MyClass(mockContentRepository.Object);
}To make your class get picked up by the NUnit test runner/the thing that runs the tests, you need to add the [TestFixture] attribute to the top of your class. In a test class you don't use a constructor, instead you create a normal method, call it wahat you want, I usually call mine Setup and decorate it with the [SetUp] attribute.
To create a test, simply create a normal method and decorate it with the [Test] attribute. Easy!
Installing and using NUnit in your project is simple. As almost 95% of the NUnit things that you need to worry about are just a few attributes you need to decorate your classes and methods, then getting up and running with NUnit is really quick. I did warn you at the beginning, the main challenge of unit testing is writing testable code, the actual framework bits are usually pretty quick to get to grips with, enjoy!
Software Architect, Programmer and Technologist Jon Jones is founder and CEO of London-based tech firm Digital Prompt. He has been working in the field for nearly a decade, specializing in new technologies and technical solution research in the web business. A passionate blogger by heart , speaker & consultant from England.. always on the hunt for the next challenge