Writing XUnit tests in C#

Writing XUnit tests in C#
Photo by Rod Long / Unsplash

XUnit is a popular open-source unit testing framework for C#. It provides a simple and extensible way to write unit tests, and is integrated with Visual Studio through the xUnit.net Visual Studio Runner extension. Here's an example of how you can write a basic unit test using xUnit in C#:

using Xunit;

public class CalculatorTests
{
    [Fact]
    public void Add_TwoNumbers_ReturnsSum()
    {
        // Arrange
        var calculator = new Calculator();
        var x = 3;
        var y = 4;

        // Act
        var result = calculator.Add(x, y);

        // Assert
        Assert.Equal(7, result);
    }
}

In this example, the CalculatorTests class contains a single test method, Add_TwoNumbers_ReturnsSum(). The test method is decorated with the [Fact] attribute, which tells xUnit that this is a test method.

The test method starts with the "Arrange" phase, where the test context is set up. In this case, it creates an instance of the Calculator class, which is the class being tested.

Then the "Act" phase is executed, where the code under test is called. In this case, it calls the Add method on the Calculator instance, passing in the values x and y as arguments.

Finally, the "Assert" phase is executed, where the results of the test are verified. In this case, it uses the Assert.Equal method to check that the result of the Add method is equal to the expected value of 7.

Xunit also provide other methods for assertions like Assert.True(), Assert.False(), Assert.NotNull(), Assert.Null(), Assert.Contains() and many more.

You can run the test by right-clicking on the test class or test method and selecting "Run Tests" or by using a test runner like the built-in test explorer in Visual Studio.