WebApi xUnit实战
提问
如何顺利开始第一个xUnit,有哪些点需要注意
回答
- Mock的接口,假如是类则方法为Vitual;
- Mock类注意构造函数的Mock,不要只Mock无参的;
- WebAPI获取Action的值需要通过as转换as OkObjectResult;
- 无关联的直接传null;
示例
[Fact]
public void GetBayByDeviceIdTest()
{
//Arrange
var id = Guid.NewGuid();
var bayApplication = new Mock<BayApplication>(null, null);
bayApplication.Setup(x => x.GetBayByDeviceId(id))
.Returns(new Bay { Id = id });
var controller = new DevicesController(null, null,null, bayApplication.Object, null);
//Act
var actual = controller.GetBayByDeviceId(id);
var o = actual as OkObjectResult;
var v = o.Value;
// Assert
Assert.IsType(typeof(Bay), v);
Assert.Equal(id, (v as Bay).Id);
}
参考
https://learn.microsoft.com/zh-cn/dotnet/core/testing/unit-testing-best-practices