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 −

  1. In Solution Explorer, right-click your solution

  2. Select "Add" ? "New Project"

  3. Choose "Unit Test Project" from the templates

  4. Set a name for your test project and click "OK"

Unit Test Project

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 data

  • Test both positive and negative scenarios

  • Keep tests independent and isolated from each other

Running Unit Tests

To run your unit tests in Visual Studio −

  1. Go to "Test" menu ? "Run" ? "All Tests"

  2. Or use the Test Explorer window to run individual tests

  3. 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.

Updated on: 2026-03-17T07:04:35+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements