Skip to content

snerte/bunit.AutoMocker

Repository files navigation

This project combines bunit and Moq.AutoMock making it super easy to create tests for Blazor Components. All dependencies are mocked automatically with AutoMocker so that you only have to setup the dependencies you use! Making test code super clean, easy to read and write.

Sample

Given Routes.razor.cs

public partial class Routes
{
    [Inject]
    IMydependency MyDependency { get; set; } = null!;

    [Inject]
    IMyOtherDependency MyOtherDependency { get; set; } = null!;

    protected override void OnInitialized()
    {
        MyDependency.GetSomeValue();
    }
}

Problem

Without AutoMocker the test setup process is tedious and requires a lot of maintenance.

public class WithoutAutoMockerTests : TestContext
{
    [Fact]
    public void MyTest()
    {
        // Arrange
        var myDependency = new Moq.Mock<IMydependency>();
        myDependency.Setup(x => x.GetSomeValue()).Returns("Hello World");

        Services.AddSingleton<IMydependency>(myDependency.Object);

        var myOtherDependency = new Moq.Mock<IMyOtherDependency>();
        Services.AddSingleton<IMyOtherDependency>(myOtherDependency.Object);

        // Act
        var cut = RenderComponent<Routes>();

        // Assert
        Assert.Contains(cut.Markup, "Hello World");
    }
}

Every dependency needs to be setup, not setting up IMyOtherDepencency will cause the test to fail:

[Fact]
public void Fails_WhenAllOnlyUsedDependencyIsRegisterd()
{
    // Arrange
    var myDependency = new Moq.Mock<IMydependency>();
    myDependency.Setup(x => x.GetSomeValue()).Returns("Hello World");

    Services.AddSingleton<IMydependency>(myDependency.Object);

    // Act & Assert
    Assert.Throws<InvalidOperationException>(() => RenderComponent<Routes>());
}

Solution

With Automocker writing tests is simple. Change TestContext to AutoMockerTestContext and use the Mocker field from the baseclass to setup AutoMocker. For more info and AutoMocker recepies, check their docs

public class AutoMockerTestContextTests : AutoMockerTestContext
{
    [Fact]
    public void CreatesUnregisteredDependencies()
    {
        // Arrange
        Mocker.Use<IMydependency>(x => x.GetSomeValue() == "Hello World");

        // Act
        var cut = RenderComponent<Routes>();

        // Assert
        Assert.Contains(cut.Markup, "Hello World");
    }
}

About

This project combines Moq.AutoMocker and bunit

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published