[英]How can i write a unit test for Action Result Ok() with a string?
我有一个关于如何编写单元测试的问题,我的方法是:
[HttpGet]
[Route("api/CheckAvailability")]
public IHttpActionResult CheckAvailability()
{
var errorMessage = "DB not connected";
var dbAvailable = barcodeManager.CheckDBAvailability();
IHttpActionResult checkAvailability;
log.Debug($"DB available ? {dbAvailable}");
if (dbAvailable)
{
Assembly assembly = Assembly.GetExecutingAssembly();
FileVersionInfo fileVersionInfo = FileVersionInfo.GetVersionInfo(assembly.Location);
string version = fileVersionInfo.ProductVersion ;
log.Debug($"version = {version}");
checkAvailability = Ok(version);
}
else
{
checkAvailability = Content(HttpStatusCode.InternalServerError, errorMessage);
}
return checkAvailability;
}
我想测试 Ok(version) 结果。 我试着写这个单元测试:
[TestMethod]
public void CheckAvailabilityTest()
{
var actualQR = barcodeControllerTest.CheckAvailability();
var contentVersion = actualQR as OkNegotiatedContentResult<string>;
Assert.AreNotEqual("", contentVersion.Content);
Assert.IsInstanceOfType(actualQR, typeof(OkResult));
}
但我收到此错误消息:
错误消息:Assert.IsInstanceOfType 失败。 预期类型:
<System.Web.Http.Results.OkResult>
。 实际类型:<System.Web.Http.Results.OkNegotiatedContentResult
1[System.String]>`。
我知道我可以通过使用Content
方法重写 Action Method 的问题,就像我为InternalServerError
所做的那样,并且我知道如何在没有任何字符串的情况下为Ok()
编写单元测试,但我认为这是不对的,我改变了我的 Action Method 来编写单元测试,因为我的单元测试必须测试我的代码,现在我很想知道是否有办法检查 ActionMethod 是否使用字符串返回Ok()
而无需使用Content
方法。
这是断言的问题,而不是被测成员的问题。
OkNegotiatedContentResult<T>
不是衍生自OkResult
以便断言将用于故障Ok<T>(T result)
从ApiController
由于您已经在转换为所需的类型,那么另一种方法是断言为 null
[TestMethod]
public void CheckAvailabilityTest() {
//Act
IHttpActionResult actualQR = barcodeController.CheckAvailability();
var contentVersion = actualQR as OkNegotiatedContentResult<string>;
//Assert
Assert.IsNotNull(contentVersion); //if null, fail
Assert.AreNotEqual("", contentVersion.Content); //otherwise check other assertion
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.