Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the Values from a Task<IActionResult> returned through an API for Unit Testing

I have created an API using ASP.NET MVC Core v2.1. One of my HttpGet methods is set up as follows:

public async Task<IActionResult> GetConfiguration([FromRoute] int? id)
{
    try
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        ..... // Some code here

        return Ok(configuration);
    }
    catch (Exception ex)
    {
        ... // Some code here
    }
}

When unit testing this I can check that Ok was the response, but I really need to see the values of the configuration. I don't seem to be able to get this to work with the following:

[TestMethod] 
public void ConfigurationSearchGetTest()
{
    var context = GetContextWithData();
    var controller = new ConfigurationSearchController(context);
    var items = context.Configurations.Count();
    var actionResult = controller.GetConfiguration(12);

    Assert.IsTrue(true);
    context.Dispose();
}

At runtime, I can check that actionResult has certain values that I am unable to code for. Is there something I am doing wrong? Or am I just thinking about this wrong? I would like to be able to do:

Assert.AreEqual(12, actionResult.Values.ConfigurationId);
like image 858
Christopher J. Reynolds Avatar asked Jun 11 '18 15:06

Christopher J. Reynolds


People also ask

What does IActionResult return?

The IActionResult return type is appropriate when multiple ActionResult return types are possible in an action. The ActionResult types represent various HTTP status codes. Any non-abstract class deriving from ActionResult qualifies as a valid return type.

Is it possible to unit test Web API?

You can either create a unit test project when creating your application or add a unit test project to an existing application. This tutorial shows both methods for creating a unit test project. To follow this tutorial, you can use either approach.


2 Answers

You can get tested controller without changing returned type.
IActionResult is base type for all others.
Cast result into expected type and compare returned value with expected.

Since you are testing asynchronous method, make test method asynchronous as well.

[TestMethod] 
public async Task ConfigurationSearchGetTest()
{
    using (var context = GetContextWithData())
    {
        var controller = new ConfigurationSearchController(context);
        var items = context.Configurations.Count();

        var actionResult = await controller.GetConfiguration(12);

        var okResult = actionResult as OkObjectResult;
        var actualConfiguration = okResult.Value as Configuration;

        // Now you can compare with expected values
        actualConfuguration.Should().BeEquivalentTo(expected);
    }
}
like image 178
Fabio Avatar answered Oct 01 '22 12:10

Fabio


Good practice would suggest that you don't have a lot of code in your controller actions to test and the bulk of logic is in decoupled objects elsewhere that are much easier to test. Having said that, if you still want to test your controllers then you need to make your test async and await the calls.

One of the problems you will have is that you are using IActionResult as it allows you to return BadRequest(...) and Ok(...). However, since you are using ASP.NET MVC Core 2.1, you may want to start using the new ActionResult<T> type instead. This should help with your testing because you can now get direct access to the strongly typed return value. For example:

//Assuming your return type is `Configuration`
public async Task<ActionResult<Configuration>> GetConfiguration([FromRoute] int? id)
{
    try
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        ..... // Some code here

        // Note we are now returning the object directly, there is an implicit conversion 
        // done for you
        return configuration;
    }
    catch (Exception ex)
    {
        ... // Some code here
    }
}

Note we are now returning the object directly as there is an implicit conversion from Foo to ActionResult<Foo>

Now your test can look like this:

[TestMethod] 
public async Task ConfigurationSearchGetTest()
{
    var context = GetContextWithData();
    var controller = new ConfigurationSearchController(context);
    var items = context.Configurations.Count();

    // We now await the call
    var actionResult = await controller.GetConfiguration(12);

    // And the value we want is now a property of the return
    var configuration = actionResult.Value;

    Assert.IsTrue(true);
    context.Dispose();
}
like image 17
DavidG Avatar answered Oct 01 '22 14:10

DavidG