11 November 2026

Testing ASP.NET Core APIs: A Beginner Guide to Unit and Integration Tests

  Asp.Net CS By Example       11 November 2026

Beginner testing tutorial

Tests are small programs that check behavior. Unit tests focus on one class or function. Integration tests exercise several pieces together, such as routing and JSON responses.

1. Create a test project

dotnet new classlib -n StudentLogic
dotnet new xunit -n StudentLogic.Tests
dotnet add StudentLogic.Tests reference StudentLogic
dotnet test

2. Test a small rule

namespace StudentLogic;

public static class GradeRules
{
    public static bool Passed(int mark) => mark >= 40;
}

Save as StudentLogic/GradeRules.cs.

using StudentLogic;

namespace StudentLogic.Tests;

public class GradeRulesTests
{
    [Fact]
    public void FortyIsPassing()
    {
        Assert.True(GradeRules.Passed(40));
    }

    [Fact]
    public void ThirtyNineIsFailing()
    {
        Assert.False(GradeRules.Passed(39));
    }
}

Save as StudentLogic.Tests/GradeRulesTests.cs and run dotnet test.

3. Choose useful cases

Test the normal case, the boundary and invalid input. A test name should explain the behavior. Keep tests independent so a failure points to one problem.

Integration testing next

ASP.NET Core supports an in-memory test server through Microsoft.AspNetCore.Mvc.Testing. A WebApplicationFactory can start the app and let a test client call real routes without opening a public port.

dotnet add package Microsoft.AspNetCore.Mvc.Testing

// Example shape:
using Microsoft.AspNetCore.Mvc.Testing;

public class ApiTests : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly HttpClient client;
    public ApiTests(WebApplicationFactory<Program> factory)
        => client = factory.CreateClient();
}

Practice

Add a GradeRules test for 100. Then write a failing test first for a rule that rejects marks below zero or above 100.

Self-check

Unit tests are fast and focused. Integration tests give stronger confidence that routing, middleware and serialization work together. Both belong in the development workflow.

Return to the .NET Core learning path · Official integration testing guide

logoblog

Thanks for reading Testing ASP.NET Core APIs: A Beginner Guide to Unit and Integration Tests

Previous
« Prev Post

No comments:

Post a Comment

Please do not enter any spam link in the comment box.