通用类型的最小起订量断言问题

Issue with Moq Assert for Generic Type

我是最小起订量的新手。

如何断言泛型类型?

测试这行出现类型错误 Assert.True(ServiceResponse<string>.Equals(result)); 有错误

Cannot access non-static method 'Equal' in static context

完整代码如下

控制器

private readonly IAuthRepository _authRepo;
public AuthController(IAuthRepository authRepo)
{
    _authRepo = authRepo;
}

[HttpPost("Register")]
public async Task<ActionResult<ServiceResponse<int>>> Register(AddUserDtos user)
{
    var response = await _authRepo.Register(user);
    if (!response.Success)
    {
        return BadRequest(response);
    }
    return Ok(response);
}        

服务响应

public class ServiceResponse<T>
{
    public T Data { get; set; }

    public bool Success { get; set; } = true;

    public string Message { get; set; } = null;
}    

测试

public class UnitTest1
{
    public Mock<IAuthRepository> repositoryStub = new Mock<IAuthRepository>();

    [Fact] 
    public async Task UnitOfWork_StateUnderTest_ExpectedBehaviour()
    {
        // Arrange
        repositoryStub.Setup(repo =>
                repo.Register(It.IsAny<AddUserDtos>()))
            .ReturnsAsync((ServiceResponse<string>) null); 

        var controller = new AuthController(repositoryStub.Object);

        AddUserDtos newUser = new AddUserDtosModel()
            {Company = "Test", Email = "email", FirstName = "", LastName = "", Password = "344343", Phone = "test"};
        // Act
        var result = await controller.Register(newUser);

        // Assert
        Assert.True(ServiceResponse<string>.Equals(result));
    }
}

首先,让我们修改排列阶段。 让我们创建一个新实例,而不是将 null 转换为 ServiceResponse<int>

// Arrange
ServiceResponse<int> response = new ServiceResponse<int>();
repositoryStub
    .Setup(repo =>repo.Register(It.IsAny<AddUserDtos>()))
    .ReturnsAsync(response); 

然后你有几个选项来确保返回的对象具有特定类型。

作为运算符和 null 检查

您可以简单地尝试将返回值转换为特定类型,然后检查是否成功:

var okResult = result as OkObjectResult;
Assert.NotNull(okResult);

var resultValue = okResult.Value as ServiceResponse<int>; 
Assert.NotNull(resultValue);

IsAssignableFrom

这里您需要做的就是用正确的 T

调用 IsAssignableFrom<T>
var okResult = Assert.IsAssignableFrom<OkObjectResult>result;
_ = Assert.IsAssignableFrom<ServiceResponse<int>>(okResult.Value); 

GetType 和 GetGenericTypeDefinition

如果需要分别检查容器class和泛型
那么你也可以这样做:

var okResult = ...;
var resultValue = okResult.Value;

Assert.NotNull(resultValue);
Assert.Equal(typeof(ServiceResponse<>), resultValue.GetType().GetGenericTypeDefinition());
Assert.IsType<int>(resultValue.Data);