问题描述
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);
}
我的测试失败了
预期在模拟上调用一次,但被调用了 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"?
还可以在亚马逊上查看“单元测试的艺术”,这本好书。