Blazor BUnit Tests with Simple Example

In this example, we discuss how to create bUnit tests for the Blazor web server-side application.

 

Open Microsoft Visual Studio 2022, create a new project => select Blazor Web Server Side => Select .Net 8 and name the project BlazorBUnitTestsExample. Add a new razor component to the project and name it CounterComponent.razor. Add the code below to CounterComponent.razor.

@page "/counter"

<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button @onclick="IncrementCount">Click me</button>

@code {

    private int currentCount = 0;

    private void IncrementCount() { currentCount++; }

}

Add a new project to the solution for tests and name it as BUnitTestProjExp. Add a project reference to BlazorBUnitTestsExample for the BUnitTestProjExp tests project. Install the Xunit and BUnit projects for BUnitTestProjExp from the Nuget project console.

 

From the Nuget package manager console, run the below commands.

Cd BUnitTestProjExp

dotnet add xunit

dotnet add package bunit.web

dotnet add package bunit.xunit

For the BUnitTestProjExp project, add CounterComponentTests.cs class for unit tests and add the code below.

using Bunit;

using BlazorBUnitTestsExample;

 

namespace BUnitTestProjExp;

public class CounterComponentTests

{

    [Fact]

    public void CounterComponentRendersCorrectly()

    {

        // Arrange

        using var ctx = new TestContext();

        var component = ctx.RenderComponent<CounterComponent>();

 

        // Act & Assert

       component.MarkupMatches("<h1>Counter</h1><p>Current count: 0</p><button>Click me</button>");

    }

 

    [Fact]

    public void CounterComponentIncrementsCount()

    {

        // Arrange

        using var ctx = new TestContext();

        var component = ctx.RenderComponent<CounterComponent>();

 

        // Act

       component.Find("button").Click();

 

        // Assert

       component.MarkupMatches("<h1>Counter</h1><p>Current count: 1</p><button>Click me</button>");

    }

}

Run the tests, and you can see all tests run successfully. Please find the explanation of the code below.

 

CounterComponent.razor: The Counter component displays a counter and a button to increment the count.

BUnitTestProjExp project: The test project uses bUnit to render the Counter component and verify its rendered output.

Test Cases: The tests check if the component renders correctly initially and if the count increments when the button is clicked.