NUnit is a popular open-source unit testing framework for .NET languages such as C# and VB.NET. It allows developers to write and run automated tests to verify the behavior of their code. NUnit supports a wide range of assertions, test fixtures, and test runners, making it a powerful tool for unit testing.
NUnit supports various features such as:
Test fixtures: A test fixture is a collection of unit tests that can be run together. NUnit provides a set of attributes that can be used to define test fixtures.
Test cases: NUnit allows developers to define test cases with different parameters, which helps to ensure that the code works correctly under different scenarios.
Assertions: NUnit provides a wide range of assertions, which can be used to test different conditions in code. Some of the commonly used assertions include Assert.AreEqual, Assert.IsTrue, and Assert.IsFalse.
Test runners: NUnit provides a command-line test runner as well as integration with various IDEs, including Visual Studio, which makes it easy to run tests and view results.
Overall, NUnit is a powerful and flexible unit testing framework that helps developers to write high-quality code by ensuring that the code works as expected.
here's an example of a test case for a simple calculator class that adds two numbers:
using NUnit.Framework; [TestFixture] public class CalculatorTests { private Calculator calculator; [SetUp] public void Setup() { // Arrange calculator = new Calculator(); } [Test] public void Add_TwoPositiveNumbers_ReturnsSum() { // Act int result = calculator.Add(2, 3); // Assert Assert.AreEqual(5, result); } [Test] public void Add_OneNegativeOnePositiveNumber_ReturnsDifference() { // Act int result = calculator.Add(-2, 3); // Assert Assert.AreEqual(1, result); } }
In this example, we have a CalculatorTests
class that contains two test cases:
Add_TwoPositiveNumbers_ReturnsSum
: This test case verifies that theAdd
method of theCalculator
class correctly adds two positive numbers and returns their sum. The test first creates a new instance of theCalculator
class in theSetup
method (which is called before each test), then calls theAdd
method with the arguments2
and3
, and finally uses theAssert.AreEqual
method to check that the result is5
.Add_OneNegativeOnePositiveNumber_ReturnsDifference
: This test case verifies that theAdd
method correctly handles one positive and one negative number by returning their difference. The test follows the same steps as the first test, but with the arguments-2
and3
, and the expected result of1
.
By running these tests, we can ensure that the Calculator
class works as expected and handles different input scenarios correctly.
No comments:
Post a Comment