预期对 Mock 调用一次,但为 0 次

Expected invocation on Mock once, but was 0 times

我有一个接口 IVehicle

public interface IVehicle
{
        Task<ApiResponse> GetVehicleInfo();
}

这是我对接口的实现

public class Vehicle : IVehicle
{
    private string m_vehicleId;        
    private VehicleInfoEndPoint m_vEndPoint;

    public Vehicle()
    {

    }
    public Vehicle(string vehicleId, string device, HttpClient client,string Uri)
    {            
        m_vEndPoint = new VehicleInfoEndPoint(device, client, Uri);
    }
    
    public async Task<ApiResponse> GetVehicleInfo()
    {
        await m_vEndPoint.GetVehicleInfoPostAsync();
        return m_vehicleInfoEndPoint.FullResponse;
    }        
}

我想对此进行单元测试 class。为此,我编写了以下代码。

    [Test]
    public void Vehicle_GetVehicleInformation_shouldCall_VehicleInfoEndPoint_GetVehicleInfo()
    {            
        var endPointMock = Mock.Of<IVehicleInfoEndPoint>();
        var result = new ApiResponse();
        var vehicle = new Mock<IVehicle>();

        vehicle.Setup(x => x.GetVehicleInfo()).Returns(Task.FromResult(result));

        var response = vehicle.Object.GetVehicleInfo().Result;
       
        Mock.Get(endPointMock).Verify(x => x.GetVehicleInfo(), Times.Once);
    }

我的测试失败,错误是

预期对模拟调用一次,但为 0 次x=> x.GetVehicleInfo()

在这种情况下,在我看来你想要测试的是 x.GetVehicleInfoPostAsync() 被调用了。

在这种情况下,您必须定义您的单元工件:

  • 车辆是您正在测试的系统
  • IVehicleInfoEndPoint 是你的模拟
  • 您想断言调用 GetVehicleInfo() 会调用模拟端点

我做了这个简单的例子来做你想要的:

class Program
{
    static async Task Main(string[] args)
    {
        // ARRANGE
        var endPointMock = Mock.Of<IVehicleInfoEndPoint>();
        var vehicle = new Vehicle(endPointMock);
        // ACT
        var response = await vehicle.GetVehicleInfo();
        // ASSERT
        Mock.Get(endPointMock).Verify(x => x.GetVehicleInfoPostAsync(), Times.Once);
    }
}
public interface IVehicle
{
    Task<ApiResponse> GetVehicleInfo();
}
public class Vehicle : IVehicle
{
    private readonly IVehicleInfoEndPoint _endpoint;
    public Vehicle(IVehicleInfoEndPoint endpoint)
    {
        _endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
    }
    public async Task<ApiResponse> GetVehicleInfo()
    {
        await _endpoint.GetVehicleInfoPostAsync();
        return _endpoint.FullResponse;
    }        
}
public interface IVehicleInfoEndPoint 
{
    Task GetVehicleInfoPostAsync();
    ApiResponse FullResponse { get; set; }
}
public class ApiResponse
{
}

将测试分为 3 个部分会有所帮助:

  • 排列
  • 行动
  • 断言

看看这个:What is a "Stub"?

还可以在亚马逊上查看“单元测试的艺术”,好书。