【发布时间】:2020-04-29 15:54:22
【问题描述】:
我有一个关于如何编写单元测试的问题,我的方法是:
[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.OkNegotiatedContentResult1[System.String]>`.
我知道我可以绕过使用方法Content 重写操作方法的问题,就像我为InternalServerError 所做的那样,并且我知道如何为Ok() 编写单元测试而不返回任何字符串,但是我认为这是不对的,我更改了我的 Action Method 来编写单元测试,因为我的单元测试必须测试我的代码,现在我很想知道是否有办法检查 ActionMethod 是否返回 Ok() 并带有字符串和不使用Content 方法。
【问题讨论】:
-
OkNegotiatedContentResult1不是从OkResult派生的
标签: c# unit-testing asp.net-web-api2