应调用Mock一次,但实际为0次



我有一个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;
}        
}

我想单元测试这个类。为此,我编写了以下代码。

[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);
}

我的测试失败了,错误是

模拟上应调用一次,但为x=> x.GetVehicleInfo()的0倍

在这种情况下,您似乎想要测试的是调用了x.GetVehicleInfoPostAsync()

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

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

我做了一个快速的例子,可以做你想要的:

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
{
}

当你把测试分成三部分时,它会有所帮助:

  • 排列
  • Act
  • 断言

看看这个:什么是";Stub"?

此外,结账";单元测试的艺术";在亚马逊上,这是一本很棒的书。

最新更新