C#, NUnit has a lot of features that makes it a good choice for testing. It provides features for writing and running tests, and also for creating test fixtures and test suites. NUnit is a popular choice for unit testing in C# due to its simplicity and extensibility.
Writing Tests
NUnit provides a set of attributes that can be used to write tests. The Test
attribute is used to mark a method as a test method. The TestCase
attribute is used to provide test data for parameterized tests. The SetUp
and TearDown
attributes are used to mark methods that should be run before and after each test method, respectively.
using NUnit.Framework;
[TestFixture]
public class CalculatorTests
{
private Calculator calculator;
[SetUp]
public void Setup()
{
calculator = new Calculator();
}
[Test]
public void Add_WhenCalled_ReturnsSumOfArguments()
{
int result = calculator.Add(2, 3);
Assert.AreEqual(5, result);
}
[Test]
[TestCase(2, 3, 5)]
[TestCase(5, 7, 12)]
public void Add_WithTestData_ReturnsSumOfArguments(int a, int b, int expected)
{
int result = calculator.Add(a, b);
Assert.AreEqual(expected, result);
}
}
Running Tests
To run the tests, dotnet test
command can be used. This command runs all the tests in the project.
dotnet test