【问题标题】:How can i write a unit test for Action Result Ok() with a string?如何使用字符串为 Action Result Ok() 编写单元测试?
【发布时间】: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 失败。预期类型:&lt;System.Web.Http.Results.OkResult&gt;。实际类型:&lt;System.Web.Http.Results.OkNegotiatedContentResult1[System.String]>`.

我知道我可以绕过使用方法Content 重写操作方法的问题,就像我为InternalServerError 所做的那样,并且我知道如何为Ok() 编写单元测试而不返回任何字符串,但是我认为这是不对的,我更改了我的 Action Method 来编写单元测试,因为我的单元测试必须测试我的代码,现在我很想知道是否有办法检查 ActionMethod 是否返回 Ok() 并带有字符串和不使用Content 方法。

【问题讨论】:

  • OkNegotiatedContentResult1 不是从 OkResult 派生的

标签: c# unit-testing asp.net-web-api2


【解决方案1】:

这是断言的问题,而不是被测成员的问题。

OkNegotiatedContentResult&lt;T&gt; 不是从OkResult 派生的,因此对于来自ApiControllerOk&lt;T&gt;(T result) 的断言将失败

由于您已经转换为所需的类型,因此另一种方法是为 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
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    • 2012-01-06
    相关资源
    最近更新 更多