How to mock static extension methods in Unit Test (c#)

256 Views Asked by At

I'm currently working on unit testing a .NET 6 project and facing a challenge with mocking static extension methods because I'm not allowed to refactor the code. I have a scenario where I need to mock a static extension method, and I'm not sure how to approach it using my testing framework (xUnit) along with a mocking library (Moq).


Below is my service:

public class AuthService : IAuthService 
{
    private readonly IDbConnection _dbConnection;

    private readonly IConfiguration _configuration;

    public AuthService(IDbConnection dbConnection, IConfiguration configuration)
    {
        _dbConnection = dbConnection;

        _configuration = configuration;
    }

    public async Task<User?> GetUserByName(string name)
    {
        return await _dbConnection.QuerySingleOrDefaultAsync<User?>("StoredProcedure", new { name }, commandType: CommandType.StoredProcedure);
    }
}

Below is my xunit test:

public  class AuthService 
{
    private AuthService _service;

    private Mock<IDbConnection> _dbConnection;

    [Fact]
    public async Task GetUserByUsername_Test()
    {
        // Arrange
        _dbConnection = new Mock<IDbConnection>();
        _service = new(_dbConnection.Object, Configuration.Config);

        var user = new User
        {
            Id = 1,
            Username = "testuser",
            Password = "Password123",
            RoleId = 1,
            StatusId = 1
        };

        _dbConnection
            .Setup(x => x.QuerySingleOrDefaultAsync<User>(
                "StoredProcedure", It.IsAny<object>(), null, null, CommandType.StoredProcedure))
        .ReturnsAsync(user);

        // Act
        var result = await _service.GetUserByName("testuser");

        // Assert
        Assert.NotNull(result);
        Assert.Equal("testuser", result.Username);
    }
}

Errors facing:

Unsupported expression: x => x.QuerySingleOrDefaultAsync<User>. Extension methods (SqlMapper.QuerySingleOrDefaultAsync) may not be used in setup / verification expressions.


I understand that in some cases, testing involving static extension methods might be more suitable for integration testing. However, my supervisor has specifically requested unit tests for this scenario. Appreciate, if any suggestions and guidance on how to effectively mock static extension methods in a unit testing context.

0

There are 0 best solutions below