简体   繁体   中英

How can i write a unit test for Action Result Ok() with a string?

I have a question about how to write a unit test, my method is:

[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;
}

and I want to test the Ok(version) result. I tried to write this unit test:

[TestMethod]
public void CheckAvailabilityTest()
{
    var actualQR = barcodeControllerTest.CheckAvailability();
    var contentVersion = actualQR as OkNegotiatedContentResult<string>;

    Assert.AreNotEqual("", contentVersion.Content);
    Assert.IsInstanceOfType(actualQR, typeof(OkResult));
}

but I get this error message:

Error Message: Assert.IsInstanceOfType failed. Expected type: <System.Web.Http.Results.OkResult> . Actual type: <System.Web.Http.Results.OkNegotiatedContentResult 1[System.String]>`.

I know I can by pass the problem rewriting the Action Method using the method Content like I did for the InternalServerError , and I know how to write a Unit Test for Ok() without any string back, but I think it is not right I change my Action Method to write the unit test because my unit test has to test my code, and now I am curious to know if there is a way to check if the ActionMethod return Ok() with a string and without using the Content method.

This is an issue with the assertion and not the member under test.

OkNegotiatedContentResult<T> is not derived from OkResult so that assertion will fail for Ok<T>(T result) from ApiController

Since you are already casting to the desired type, then an alternative would be to assert for 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM