Web API  

Unit testing for a .NET Web API project.

1. Set up Unit Testing Project

When you create a new Web API project in .NET 8, you can add a test project separately:

dotnet new xunit -n MyApi.Tests
dotnet add MyApi.Tests reference MyApi

Here

  • MyApi → your main Web API project

  • MyApi.Tests → your test project

You can use xUnit (default choice), or NUnit / MSTest, depending on preference.

xUnit is most commonly used in the .NET Core ecosystem.

2. Install Required NuGet Packages

Inside your test project:

dotnet add package xunit
dotnet add package xunit.runner.visualstudio
dotnet add package FluentAssertions
dotnet add package Moq
  • xUnit → testing framework

  • FluentAssertions → readable assertions (e.g., result.Should().Be(200))

  • Moq → mocking dependencies

3. Structure of the Solution

MyApi/
  Controllers/
    WeatherController.cs
  Services/
    IWeatherService.cs
    WeatherService.cs
MyApi.Tests/
  Controllers/
    WeatherControllerTests.cs
  Services/
    WeatherServiceTests.cs

4. Writing Unit Tests for a Service

Suppose you have a service:

public interface IWeatherService
{
    int GetTemperature(string city);
}

public class WeatherService : IWeatherService
{
    public int GetTemperature(string city)
    {
        if (city == "Delhi") return 35;
        return 25;
    }
}

Unit Test Example

using Xunit;
using FluentAssertions;
using MyApi.Services;

public class WeatherServiceTests
{
    [Fact]
    public void GetTemperature_ShouldReturn35_WhenCityIsDelhi()
    {
        // Arrange
        var service = new WeatherService();

        // Act
        var result = service.GetTemperature("Delhi");

        // Assert
        result.Should().Be(35);
    }
}

5. Writing Unit Tests for a Controller

Suppose you have a controller:

[ApiController]
[Route("api/[controller]")]
public class WeatherController : ControllerBase
{
    private readonly IWeatherService _weatherService;

    public WeatherController(IWeatherService weatherService)
    {
        _weatherService = weatherService;
    }

    [HttpGet("{city}")]
    public IActionResult GetWeather(string city)
    {
        var temp = _weatherService.GetTemperature(city);
        return Ok(new { City = city, Temperature = temp });
    }
}

Unit Test with Mocking Dependency

using Xunit;
using FluentAssertions;
using Moq;
using Microsoft.AspNetCore.Mvc;
using MyApi.Controllers;
using MyApi.Services;

public class WeatherControllerTests
{
    [Fact]
    public void GetWeather_ShouldReturnOkWithTemperature()
    {
        // Arrange
        var mockService = new Mock<IWeatherService>();
        mockService.Setup(s => s.GetTemperature("Delhi")).Returns(35);

        var controller = new WeatherController(mockService.Object);

        // Act
        var result = controller.GetWeather("Delhi") as OkObjectResult;

        // Assert
        result.Should().NotBeNull();
        result!.StatusCode.Should().Be(200);

        var response = result.Value as dynamic;
        ((int)response.Temperature).Should().Be(35);
    }
}

6. Running Tests

Run tests using:

dotnet test

7. Best Practices

  • Test only logic, not infrastructure (e.g., don’t test DB directly in unit tests → use integration tests for that).

  • Use Moq or other mocking frameworks for dependencies.

  • Follow the AAA Pattern: Arrange → Act → Assert.

  • Keep tests independent (no shared state).

  • For Web API end-to-end testing, consider WebApplicationFactory in integration tests.