.NET Testing with NUnit
The software we write should go through the testing phase. There are many testing frameworks available. Out of these testing frameworks, NUnit is one of famous, rich in features, developer's favourite automated testing framework.
In this topic, I provide how to set up and key features of NUnit.
Enabling NUnit Test Execution in Visual Studio
I'm using Visual Studio 2017, select your test project, on reference, right click and select Manage Nuget. Install
- NUnit
- Nunit Test Adapter
NUnit Attributes
[TestFixture] : This is annotation for test class
[Test]: This is annotation for test method
Assert: This is used tell test runner to tell whether the test is pass or fail.
eg:-
[TestFixture]
public class CalculatorTests
{
[Test]
public void ShouldSubtractTwoNegativeNumbers()
{
var sut = new Calculator();
sut.Subtract(-5);
sut.Subtract(-10);
Assert.That(sut.CurrentValue, Is.EqualTo(15));
}
}
Attribute levels
We can set up attributes in
- Method Level
- Class Level
- Namespace or Assembly Level
- Entire Assembly
Method Level
[SetUP]: Before each test run, setup method will execute.
[TearDown]: After each test executes, teardown method will execute.
Class Level
[TestFixtureSetUP]: (Class level)
[TestFixtureTearDown]: (Class level)
Namespace or Assembly Level
namespace Attributes.Tests.SomeNamespace
{
[SetUpFixture]
public class SetUpFixtureForSpecificNamespace
{
[SetUp]
public void RunBeforeAnyTestsInSomeNamespace()
{
Console.WriteLine("Before any tests in SomeNamespace");
}
[TearDown]
public void RunAfterAnyTestsInSomeNamespace()
{
Console.WriteLine("After all tests in SomeNamespace");
}
}
}
For Entire Assembly
// Notice no containing namespace for this class
[SetUpFixture]
public class SetUpFixtureForEntireAssembly
{
[SetUp]
public void RunBeforeAnyTestsInEntireAssembly()
{
Console.WriteLine("Before any tests in entire assembly");
}
[TearDown]
public void RunAfterAnyTestsInInEntireAssembly()
{
Console.WriteLine("After all tests in entire assembly");
}
}