C# Interview Question #96

What is unit testing in C#?

SOLID, DI, Testing & Practical C# Mid-Level Intermediate

Quick Interview Answer

Unit testing verifies a small unit of behavior, such as a method or service, in isolation from unrelated infrastructure.

Detailed Explanation

Unit testing verifies a small unit of behavior, such as a method or service, in isolation from unrelated infrastructure.

Popular .NET testing frameworks include xUnit, NUnit, and MSTest. Mocking libraries such as Moq, NSubstitute, or FakeItEasy can replace external dependencies when appropriate.

Good unit tests are deterministic, focused, readable, and fast. They normally follow a structure such as Arrange, Act, Assert.

Code Example

[Fact]
public void Add_ShouldReturnSum()
{
    // Arrange
    var calculator = new Calculator();

    // Act
    int result = calculator.Add(2, 3);

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