How to Use NUnit in C#: Simple Guide with Examples
To use
NUnit in C#, install the NUnit and NUnit3TestAdapter packages, write test methods marked with [Test] inside a class marked with [TestFixture], and run tests using a test runner like Visual Studio Test Explorer. NUnit helps you check if your code works by running automated tests.Syntax
In NUnit, you create a test class with the [TestFixture] attribute. Inside it, each test method has the [Test] attribute. Use Assert methods to check expected results.
[TestFixture]: Marks a class as containing tests.[Test]: Marks a method as a test case.Assert: Used to verify conditions in tests.
csharp
using NUnit.Framework; [TestFixture] public class CalculatorTests { [Test] public void Add_TwoNumbers_ReturnsSum() { int result = 2 + 3; Assert.AreEqual(5, result); } }
Example
This example shows a simple test for a calculator's addition method. It checks if adding 2 and 3 returns 5.
csharp
using NUnit.Framework; public class Calculator { public int Add(int a, int b) => a + b; } [TestFixture] public class CalculatorTests { private Calculator calculator; [SetUp] public void Setup() { calculator = new Calculator(); } [Test] public void Add_TwoNumbers_ReturnsSum() { int result = calculator.Add(2, 3); Assert.AreEqual(5, result); } }
Output
Test Passed
Common Pitfalls
Common mistakes include forgetting to add the [Test] attribute, which means the method won't run as a test, or not installing NUnit packages properly. Also, avoid writing tests that depend on each other; each test should be independent.
csharp
using NUnit.Framework; [TestFixture] public class WrongTests { // This method won't run as a test because it lacks [Test] public void MissingTestAttribute() { Assert.Pass(); } [Test] public void CorrectTest() { Assert.Pass(); } }
Quick Reference
- Use
[TestFixture]on test classes. - Use
[Test]on test methods. - Use
Assertto check results. - Install
NUnitandNUnit3TestAdaptervia NuGet. - Run tests with Visual Studio Test Explorer or other runners.
Key Takeaways
Mark test classes with [TestFixture] and test methods with [Test] to create NUnit tests.
Use Assert methods to verify that your code behaves as expected.
Install NUnit and NUnit3TestAdapter packages to enable testing in your project.
Each test should be independent and have the [Test] attribute to run correctly.
Run tests easily using Visual Studio Test Explorer or compatible test runners.