Unit testing is a crucial aspect of software development, ensuring that each component of your application functions as intended. NUnit is a popular testing framework for C# that allows developers to write and execute tests efficiently. In this article, we will explore three diverse, practical examples of C# unit testing using NUnit. These examples will provide clear contexts and explanations to help you understand how to implement unit tests in your projects.
In this example, we will create unit tests for a basic calculator class that performs addition and subtraction. This is a common use case for unit testing, as it ensures that basic arithmetic operations produce the expected results.
using NUnit.Framework;
public class Calculator
{
public int Add(int a, int b) => a + b;
public int Subtract(int a, int b) => a - b;
}
[TestFixture]
public class CalculatorTests
{
private Calculator _calculator;
[SetUp]
public void Setup()
{
_calculator = new Calculator();
}
[Test]
public void Add_WhenCalled_ReturnsSum()
{
var result = _calculator.Add(5, 3);
Assert.AreEqual(8, result);
}
[Test]
public void Subtract_WhenCalled_ReturnsDifference()
{
var result = _calculator.Subtract(5, 3);
Assert.AreEqual(2, result);
}
}
[SetUp]
attribute ensures that a new instance of the Calculator
class is created before each test.Assert.AreEqual
to verify the correctness of the methods.Here, we will write unit tests for a class that performs string manipulations, such as reversing a string and checking if it is a palindrome. This example showcases how to test methods that handle strings effectively.
using NUnit.Framework;
public class StringManipulator
{
public string Reverse(string input) => new string(input.Reverse().ToArray());
public bool IsPalindrome(string input) => input == Reverse(input);
}
[TestFixture]
public class StringManipulatorTests
{
private StringManipulator _stringManipulator;
[SetUp]
public void Setup()
{
_stringManipulator = new StringManipulator();
}
[Test]
public void Reverse_WhenCalled_ReturnsReversedString()
{
var result = _stringManipulator.Reverse("hello");
Assert.AreEqual("olleh", result);
}
[Test]
public void IsPalindrome_WhenCalled_ReturnsTrueForPalindrome()
{
var result = _stringManipulator.IsPalindrome("madam");
Assert.IsTrue(result);
}
[Test]
public void IsPalindrome_WhenCalled_ReturnsFalseForNonPalindrome()
{
var result = _stringManipulator.IsPalindrome("hello");
Assert.IsFalse(result);
}
}
IsPalindrome
provide clear cases for both true and false outcomes, illustrating how to assert boolean values.In this final example, we will test an asynchronous method that fetches data from a simulated API. This is particularly useful when dealing with modern applications that rely on asynchronous programming for better performance.
using NUnit.Framework;
using System.Net.Http;
using System.Threading.Tasks;
public class ApiService
{
private readonly HttpClient _httpClient;
public ApiService(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<string> GetDataAsync(string url)
{
var response = await _httpClient.GetStringAsync(url);
return response;
}
}
[TestFixture]
public class ApiServiceTests
{
private ApiService _apiService;
private HttpClient _httpClient;
[SetUp]
public void Setup()
{
_httpClient = new HttpClient(); // Mocked or real HttpClient can be used
_apiService = new ApiService(_httpClient);
}
[Test]
public async Task GetDataAsync_ValidUrl_ReturnsData()
{
var result = await _apiService.GetDataAsync("https://jsonplaceholder.typicode.com/posts/1");
Assert.IsNotNull(result);
Assert.IsTrue(result.Contains("userId"));
}
}
HttpClient
to control the responses received during testing.These examples of C# unit testing with NUnit illustrate the power of unit tests in ensuring the functionality of your code across various scenarios. Utilizing NUnit’s features, you can create robust tests that enhance the reliability of your software.