c#-xUnit.net IsType在MS测试中等效,返回类型
作者:互联网
我正在追踪this guide,并且尝试使用MS Test编写类似的测试. MS Test是否有一个IsType()
,当强制转换成功时会返回对象?
从this comparison开始,我可以使用IsInstanceOfType(),但返回类型为void.
我正在尝试在MS Test中实现这一行:
var badRequestResult = Assert.IsType< BadRequestObjectResult>(结果);
[Fact]
public async Task IndexPost_ReturnsBadRequestResult_WhenModelStateIsInvalid()
{
// Arrange
var mockRepo = new Mock<IBrainstormSessionRepository>();
mockRepo.Setup(repo => repo.ListAsync()).Returns(Task.FromResult(GetTestSessions()));
var controller = new HomeController(mockRepo.Object);
controller.ModelState.AddModelError("SessionName", "Required");
var newSession = new HomeController.NewSessionModel();
// Act
var result = await controller.Index(newSession);
// Assert
var badRequestResult = Assert.IsType<BadRequestObjectResult>(result);
Assert.IsType<SerializableError>(badRequestResult.Value);
}
是的,我可以先使用as进行转换,然后再使用IsInstanceOfType……只是想知道是否有单线.
var badRequestResult = result as BadRequestObjectResult;
Assert.IsInstanceOfType(badRequestResult, typeof(BadRequestObjectResult));
解决方法:
我从未遇到过MSTest中的等效版本.
如果是强制类型转换,则无需检查实例是否为类型.只要检查它是否不为空.
// Act
var result = await controller.Index(newSession);
// Assert
var badRequestResult = result as BadRequestObjectResult;
Assert.IsNotNull(badRequestResult, "Expected BadRequestObjectResult");
Assert.IsInstanceOfType(badRequestResult.Value,typeof(SerializableError));
否则,您可以创建自己的断言
public static class AssertExtension {
public static TExpected AssertIsType<TExpected>(this object actual, string message = null) {
TExpected result = actual as TExpected;
Assert.IsNotNull(result, message);
return result;
}
}
提供所需的行为
// Assert
var badRequestResult = result.AssertIsType<BadRequestObjectResult>();
badRequestResult.Value.AssertIsType<SerializableError>();
标签:xunit-net,mstest,c 来源: https://codeday.me/bug/20191109/2011418.html