Writing Tests with C# Unit Testing


What is Unit Testing with C#?

C# unit testing is a method of testing whether certain parts of your application (usually functions or classes) work correctly during the software development process. This method allows developers to add reliability to their code. Unit testing facilitates the debugging process and increases overall software quality.

Unit tests are usually written as independent tests. Each test checks how a particular function behaves in a specific situation, as determined by the developer. These tests help detect errors that may occur when changes are made to the code at an early stage.

Before Starting to Write Unit Tests

Required Libraries

To write unit tests with C#, the Microsoft.VisualStudio.TestTools.UnitTesting or NUnit library is usually used. You can add these libraries to your project via the NuGet package manager.

Install-Package NUnit
Install-Package NUnit3TestAdapter

A Simple Unit Test Example

Below you can see an example unit test for a simple addition operation. First, we created a class to be tested.

public class Calculator {
    public int Add(int a, int b) {
        return a + b;
    }
}

Now let's write a unit test to test this class:

using NUnit.Framework;

[TestFixture]
public class CalculatorTests {
    [Test]
    public void Add_TwoPositiveNumbers_ReturnsSum() {
        // Arrange
        var calculator = new Calculator();
        int a = 5;
        int b = 3;

        // Act
        int result = calculator.Add(a, b);

        // Assert
        Assert.AreEqual(8, result);
    }
}

Conclusion

C# unit testing is critically important in the software development process. The tests you write increase the reliability of your applications and make debugging easier. In this article, you learned the basics of writing unit tests with C#. Remember, the more tests you write, the more reliable software you will deliver.