Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Unit Testing for C# Code
Unit testing is a fundamental practice in C# development that helps maintain code quality throughout the development process. It allows developers to identify problems early in the development cycle and ensures code reliability and reusability.
One of the key principles of effective unit testing is following Test Driven Development (TDD) approach, where you write test cases first, then write the minimal code required to make those tests pass.
Setting Up Unit Tests in Visual Studio
For unit testing in C#, you can use Microsoft's built-in testing framework, commonly known as MS Unit Test. Here's how to create a unit test project −
In Solution Explorer, right-click your solution
Select "Add" ? "New Project"
Choose "Unit Test Project" from the templates
Set a name for your test project and click "OK"
Basic Unit Test Structure
A typical unit test follows the Arrange-Act-Assert pattern. Here's the basic syntax −
[TestMethod]
public void TestMethodName() {
// Arrange: Set up test data
// Act: Execute the method being tested
// Assert: Verify the expected result
}
Creating Your First Unit Test
Let's create a simple calculator class and write unit tests for it −
Calculator Class
using System;
public class Calculator {
public int Add(int a, int b) {
return a + b;
}
public int Subtract(int a, int b) {
return a - b;
}
public int Multiply(int a, int b) {
return a * b;
}
public double Divide(int a, int b) {
if (b == 0)
throw new DivideByZeroException("Cannot divide by zero");
return (double)a / b;
}
}
Unit Test Class
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
[TestClass]
public class CalculatorTests {
private Calculator calculator;
[TestInitialize]
public void Setup() {
calculator = new Calculator();
}
[TestMethod]
public void Add_TwoPositiveNumbers_ReturnsCorrectSum() {
// Arrange
int a = 5;
int b = 3;
int expected = 8;
// Act
int result = calculator.Add(a, b);
// Assert
Assert.AreEqual(expected, result);
}
[TestMethod]
public void Subtract_TwoNumbers_ReturnsCorrectDifference() {
// Arrange
int a = 10;
int b = 4;
int expected = 6;
// Act
int result = calculator.Subtract(a, b);
// Assert
Assert.AreEqual(expected, result);
}
[TestMethod]
[ExpectedException(typeof(DivideByZeroException))]
public void Divide_ByZero_ThrowsException() {
// Arrange
int a = 10;
int b = 0;
// Act
calculator.Divide(a, b);
// Assert is handled by ExpectedException attribute
}
}
Common Test Attributes
| Attribute | Purpose |
|---|---|
[TestClass] |
Marks a class as containing test methods |
[TestMethod] |
Marks a method as a test case |
[TestInitialize] |
Runs before each test method |
[TestCleanup] |
Runs after each test method |
[ExpectedException] |
Expects a specific exception to be thrown |
Common Assert Methods
Assert.AreEqual(expected, actual); // Values are equal Assert.AreNotEqual(expected, actual); // Values are not equal Assert.IsTrue(condition); // Condition is true Assert.IsFalse(condition); // Condition is false Assert.IsNull(object); // Object is null Assert.IsNotNull(object); // Object is not null
Best Practices
Use descriptive test method names that explain what is being tested
Follow the Arrange-Act-Assert pattern for clarity
Test one specific behavior per test method
Use
[TestInitialize]to set up common test dataTest both positive and negative scenarios
Keep tests independent and isolated from each other
Running Unit Tests
To run your unit tests in Visual Studio −
Go to "Test" menu ? "Run" ? "All Tests"
Or use the Test Explorer window to run individual tests
View results in the Test Explorer to see which tests passed or failed
Conclusion
Unit testing in C# using Microsoft's testing framework helps ensure code quality and reliability. By following TDD practices and writing comprehensive test cases, developers can catch bugs early and maintain robust, testable code throughout the development lifecycle.
