This is an old revision of the document!
Unit Testing with NUnit
Installation
- Using NUnit Test Runner:
- Download copy from NUnit Downloads.
- Install or unpack in a folder.
- Using Test Explorer in VS [Optional]:
- Install Visual Studio extension (Tools > Extensions and Updates): NUnit Test Adapter for Visual Studio.
- Add a reference to
NUnit.Framework.dll
in project (or Solution)- Manually: Project > References > right-click > Add References > Find path for
NUnit.Framework.dll
and select it. - Automatically: Using NuGet NUnit package (see https://www.nuget.org/packages/NUnit): Select project > right-click > Manage NuGet Packages > All > Add 'NUnit'.
Usage
Create test class in project, including all necessary test cases.
- See Example.
Create basic test class for testing unit TTools
in file Acme.App.Localization\Tools.cs
:
- file ToolsTest.cs
using System; using System.Collections.Generic; using System.Linq; using System.Text; using NUnit.Framework; namespace Acme.App.Localization { ///============================================================================================ /// <summary> /// Class TTools /// </summary> ///============================================================================================ [TestFixture] [Category("TTools")] class ToolsTest { [SetUp] public void Init() { } [TearDown] public void CleanUp() { } [Test, Description("Check Something Exists")] public void CheckSomethingExists() { Assert.AreEqual(Something, true); } } }
Run Tests
- Using Test Explore in VS:
- Test > Windows > Text Explorer.
- Run tests using Unit Test Explorer > Run All.
- Using NUnit Test Runner:
- Run Test Runner, and create new Test project (File > New Project).
- Select assembly or application containing unit tests (Project > Add Assembly). Note: These assemblies and applications must have a reference to
NUnit.Framework.dll
in their individual projects.
Pattern AAA
Modern tests contain three parts: [TestMethod] public void GetCount_ItemCountIsZero_NoNewMessages() {
//Arrange Mailbox mailbox = new Mailbox(); //Act var result = mailbox.GetCount(0); //Assert Assert.AreEqual("No new messages.", result);
}
- Arrange: setup everything needed for the running the tested code. This includes any initialization of dependencies, mocks and data needed for the test to run.
- Act: Invoke the code under test.
- Assert: Specify the pass criteria for the test, which fails it if not met.