Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
Skip to content
World desk5 min

How to Test FizzBuzz in ASP.NET Core with xUnit

A practical guide to testing FizzBuzz in ASP.NET Core: define the contract, unit test the rule with xUnit, and add a WebApplicationFactory integration test for the HTTP endpoint on .NET 10.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To test FizzBuzz in an ASP.NET Core application, keep the rule in a plain C# method, cover that method with xUnit unit tests, and add a small integration test that calls the HTTP endpoint through WebApplicationFactory<Program>. Separating the two layers means an arithmetic mistake and a routing or hosting mistake fail in different tests, which makes the cause obvious.

Define the contract before writing tests

ASP.NET Core does not define what FizzBuzz returns. The rules below are the conventional teaching contract, and this tutorial adopts them as its own choice:

As an Amazon Associate I earn from qualifying purchases.

Input Result Rule
1, 2, 7 The number as text Not divisible by 3 or 5
3, 9 Fizz Divisible by 3 only
5, 10 Buzz Divisible by 5 only
15, 30 FizzBuzz Divisible by both 3 and 5
0, -3 An ArgumentOutOfRangeException Outside the chosen domain of 1 and above

The invalid-input row is a decision, not a requirement. Some implementations return an error string, others clamp the input, and the endpoint can translate the exception into a 400 response. Whatever you choose, write it down and test it, because the tests become the specification.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Set up the projects

The web application and the test project should target the same framework. The Microsoft Learn page on integration tests in ASP.NET Core that this article relies on is written for ASP.NET Core 10.0, so the steps below use net10.0. If you target a different framework, check the matching version of the testing package before copying the commands.

  1. Create the web application with the empty minimal template:
    dotnet new web -f net10.0 -n FizzBuzzApp
  2. Create an xUnit test project next to it:
    dotnet new xunit -f net10.0 -n FizzBuzzApp.Tests
  3. Reference the web project from the test project:
    dotnet add FizzBuzzApp.Tests/FizzBuzzApp.Tests.csproj reference FizzBuzzApp/FizzBuzzApp.csproj
  4. Add the integration-testing package. Use the 10.0 major version so it matches the framework:
    dotnet add FizzBuzzApp.Tests/FizzBuzzApp.Tests.csproj package Microsoft.AspNetCore.Mvc.Testing --version 10.0.*
  5. Open FizzBuzzApp.Tests.csproj and confirm it contains <TargetFramework>net10.0</TargetFramework>. If the template chose another value, change it to match the web project.

Write the FizzBuzz logic as ordinary code

The rule does not need ASP.NET Core. Put it in a static class with no web types, so it can be tested directly and reused from any caller.

namespace FizzBuzzApp;

public static class FizzBuzz
{
    public static string Convert(int number)
    {
        if (number < 1)
            throw new ArgumentOutOfRangeException(nameof(number), "Must be 1 or greater.");

        if (number % 15 == 0) return "FizzBuzz";
        if (number % 3 == 0) return "Fizz";
        if (number % 5 == 0) return "Buzz";
        return number.ToString();
    }
}

Checking for 15 before 3 and 5 is what makes the combined case work. If the order is reversed, 15 returns Fizz and the tests below will catch it.

Unit tests for the transformation

Microsoft’s guidance on integration tests states the division of labour directly: “Use unit tests for routine tests of method logic that interact with these components.” Here the method under test is FizzBuzz.Convert, so every rule case belongs in a unit test. These tests create no host and run in milliseconds.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
using FizzBuzzApp;
using Xunit;

public class FizzBuzzTests
{
    [Theory]
    [InlineData(1, "1")]
    [InlineData(2, "2")]
    [InlineData(7, "7")]
    public void ReturnsNumberWhenNotDivisibleByThreeOrFive(int input, string expected)
        => Assert.Equal(expected, FizzBuzz.Convert(input));

    [Theory]
    [InlineData(3, "Fizz")]
    [InlineData(9, "Fizz")]
    public void ReturnsFizzForMultiplesOfThree(int input, string expected)
        => Assert.Equal(expected, FizzBuzz.Convert(input));

    [Theory]
    [InlineData(5, "Buzz")]
    [InlineData(10, "Buzz")]
    public void ReturnsBuzzForMultiplesOfFive(int input, string expected)
        => Assert.Equal(expected, FizzBuzz.Convert(input));

    [Theory]
    [InlineData(15, "FizzBuzz")]
    [InlineData(30, "FizzBuzz")]
    public void ReturnsFizzBuzzForMultiplesOfBoth(int input, string expected)
        => Assert.Equal(expected, FizzBuzz.Convert(input));

    [Theory]
    [InlineData(0)]
    [InlineData(-3)]
    public void ThrowsForInputBelowOne(int input)
        => Assert.Throws<ArgumentOutOfRangeException>(() => FizzBuzz.Convert(input));
}

Two optional additions are useful. A sequence test can compare the output for 1 through 100 with an expected list, which catches ordering mistakes that single values miss. The length of that list is a choice of this tutorial, not a property ASP.NET Core requires. A second option is a check that the method never returns null or an empty string for valid input.

Integration test for the HTTP endpoint

An integration test earns its place when something other than the arithmetic can break: the route, the parameter binding, the status code, or the response format. Add a route to the web project. Because this project uses top-level statements, the generated Program class is internal, so the test project cannot see it until you make it public.

using FizzBuzzApp;

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.MapGet("/fizzbuzz/{n:int}", (int n) =>
{
    if (n < 1)
        return Results.BadRequest("Number must be 1 or greater.");

    return Results.Text(FizzBuzz.Convert(n));
});

app.Run();

public partial class Program { }

The test host starts the application in memory, so no port is opened. The test below checks the web boundary, not every arithmetic case:

using System.Net;
using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;

public class FizzBuzzEndpointTests : IClassFixture<WebApplicationFactory<Program>>
{
    private readonly HttpClient _client;

    public FizzBuzzEndpointTests(WebApplicationFactory<Program> factory)
    {
        _client = factory.CreateClient();
    }

    [Fact]
    public async Task GetFizzBuzz_ReturnsOkWithFizzBuzzForFifteen()
    {
        var response = await _client.GetAsync("/fizzbuzz/15");

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        Assert.Equal("FizzBuzz", await response.Content.ReadAsStringAsync());
    }

    [Fact]
    public async Task GetFizzBuzz_ReturnsBadRequestForZero()
    {
        var response = await _client.GetAsync("/fizzbuzz/0");

        Assert.Equal(HttpStatusCode.BadRequest, response.StatusCode);
    }
}

The first test confirms that the route, binding, and text response work together. The second confirms that the boundary rule is enforced at the HTTP layer, where it turns into a status code. Neither test repeats the Fizz, Buzz, or number cases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Run the tests and read the results

From the solution folder, run:

dotnet test FizzBuzzApp.Tests/FizzBuzzApp.Tests.csproj

A successful run ends with a summary line beginning Passed! and reports zero failures. xUnit lists each [InlineData] row as its own test, so a failure names the exact input that broke.

Best Value
Sale
Programming ASP.NET Core (Developer Reference)
  • Applying all key ASP.NET Core components, including MVC for HTML generation, .NET Core, EF Core, ASP.NET Identity, dependency injection, and more
  • Integrating ASP.NET Core with leading client-side frameworks, including Bootstrap
  • ASP.NET Core code for implementing business logic and data transformations
  • Handling configuration, routing, controllers, views, and common tasks (including posting forms and presenting data)
  • Performing complementary tasks: error handling, logging, application design, authentication, localization, and more

Failure modes to recognise

  • A 404 for a non-numeric path such as /fizzbuzz/abc: the :int route constraint rejects the request before your code runs. This is expected behaviour, so assert it only if you want to lock it in.
  • A 500 instead of a 400 for zero or negative input: the exception was not translated. Keep the explicit check in the endpoint, as shown above, rather than letting the exception escape.
  • Restore or build errors in the test project: the test project and web project target different frameworks, or the Microsoft.AspNetCore.Mvc.Testing version does not match the framework. Align both to net10.0 and the 10.0 package line.
  • An error that WebApplicationFactory<Program> cannot find Program: the public partial class Program { } declaration is missing, or the application uses a namespace or a different entry-point type.

Further reading

For a broader walkthrough of C# testing, the O’Reilly book Practical Test-Driven Development using C# 7 includes xUnit and FizzBuzz exercises in its contents. It is not an ASP.NET Core FizzBuzz manual, so treat it as general background. Microsoft’s integration-testing guide for ASP.NET Core remains the primary reference for the test host setup.

The Bottom Line

Test the FizzBuzz rule with xUnit unit tests against a plain static method, then add one integration test per concern at the HTTP boundary. Keep the arithmetic in the unit tests and the routing, status codes, and response format in the endpoint tests.

Quick Recap

Bestseller No. 2
SaleBestseller No. 5
Programming ASP.NET Core (Developer Reference)
Programming ASP.NET Core (Developer Reference)
Integrating ASP.NET Core with leading client-side frameworks, including Bootstrap; ASP.NET Core code for implementing business logic and data transformations
$24.99

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.