Mocked Function using Moq being called in BUnit test

I am attempting to mock a public async method in C#, using Moq, as part of the testing setup for the rendering of a Blazor Component, but the code within the method that is being mocked is being called. This seems like a very straight forward setup so I am unclear as to why the mocking of this method is not functioning as intended.

I have removed/edited the code to maintain confidentiality of this project but the error is occurring because _authenticationStateProvider.GetAuthenticationStateAsync() is being called in Service.MockedMethod(). The error is System.NullReferenceException: ‘Object reference not set to an instance of an object.’ because authState is set to null

MyComponentTests.cs File

internal class MyComponentTests : BunitTestContext
{
    private Mock<AuthenticationStateProvider> _mockServiceProvider;
    private Mock<IAuthenticationStateService> _mockAuthenticationStateService;

    [SetUp]
    public void Setup()
    {  
        _mockServiceProvider = new Mock<AuthenticationStateProvider>();
        _mockAuthenticationStateService = new Mock<IAuthenticationStateService>();

        Services.AddSingleton<IAuthenticationStateService>(new AuthenticationService(_mockServiceProvider.Object));
    }

    [Test]
    public void MyComponentRendersCorrectly()
    {
        _mockAuthenticationStateService.Setup(s => s.MockedMethod()).ReturnsAsync("user");

        var cut = RenderComponent<MyComponent>();

        cut.MarkupMatches("<h1>TEST</h1>");
    }
}

MyComponent.CS File

@inject AuthenticationStateService service

@code {
    protected override void OnInitialized()
    {
        UserName = service.MockedMethod().Result;
    }
}

Service.CS File

namespace Services;

public class AuthenticationStateService(AuthenticationStateProvider authenticationStateProvider) : IService
{
    private readonly AuthenticationStateProvider _authenticationStateProvider = authenticationStateProvider;

    public async Task<string> MockedMethod()
    {
        AuthenticationState authState = await _authenticationStateProvider.GetAuthenticationStateAsync();
        ClaimsPrincipal user = authState.User;

        if (user?.Identity is not null && user.Identity.IsAuthenticated && user?.Identity.Name is not null)
        {
            return user.Identity.Name.Split('@')[0].ToUpper();
        }
        else
        {
            return "UNKNOWN";
        }
    }

Blazor Test Project CS File

<Project Sdk="Microsoft.NET.Sdk.Razor">

    <PropertyGroup>
        <TargetFramework>net8.0</TargetFramework>
        <Nullable>enable</Nullable>
        <IsPackable>false</IsPackable>
    </PropertyGroup>

    <ItemGroup>
        <Using Include="Bunit" />
        <Using Include="Bunit.TestDoubles" />
        <Using Include="Microsoft.Extensions.DependencyInjection" />
        <Using Include="NUnit.Framework" />
    </ItemGroup>

    <ItemGroup>
        <PackageReference Include="Moq.EntityFrameworkCore" Version="8.0.1.2" />
        <PackageReference Include="bunit" Version="1.29.5" />
        <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.10.0" />
        <PackageReference Include="coverlet.collector" Version="6.0.0">
            <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
            <PrivateAssets>all</PrivateAssets>
        </PackageReference>
    </ItemGroup>


    <ItemGroup>
        <PackageReference Include="NUnit" Version="3.14.0" />
        <PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
    </ItemGroup>


</Project>

New contributor

user26425271 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật