0

I'm trying to write some tests to some of our controllers. To keep it simple I'll use a simple class as example.

Imagine that I've a controller that returns an json object on success using Json function inherited from Controller

[ApiController]
[Route("[controller]")]
public class ExampleController:Controller
{
    [HttpGet]
    public async Task<IActionResult> Get()
    {
        return await Task.FromResult(new OkObjectResult(new {Message="Success"}));
    }

    [HttpGet("json")]
    public async Task<IActionResult> GetJson()
    {
        return await Task.FromResult(Json(new { Message = "Success" }));
    }
}

Then I have the following test methods:

        [TestMethod]
        public void TestOkResult()
        {

            var services = new ServiceCollection();
            services.AddScoped<ExampleController>();
            var controller = services.BuildServiceProvider().GetRequiredService<ExampleController>();
            var result = controller.Get().Result;
            var parsedResult = result as OkObjectResult;
            Assert.IsInstanceOfType<OkObjectResult>(result);
            Assert.AreEqual(200, parsedResult?.StatusCode ?? 500);


        }
        [TestMethod]
        public void TestJsonResult()
        {

            var services = new ServiceCollection();
            services.AddScoped<ExampleController>();
            var controller = services.BuildServiceProvider().GetRequiredService<ExampleController>();
            var result = controller.GetJson().Result;
            var parsedResult = result as JsonResult;
            Assert.IsInstanceOfType<JsonResult>(result);
            Assert.AreEqual(200, parsedResult?.StatusCode ?? 500);

        }

The method TestJsonResult can't assert the status code, because it's always null

Any ideas?

Vinicius Andrade
  • 151
  • 1
  • 4
  • 22
  • 1
    `Json` method on a `Controller` is using default constructor of `JsonResult` which is not setting StatusCode by default. You have to do it yourself: `new JsonResult(new { Message = "Success" }) { StatusCode = StatusCodes.Status200OK }`. More about it in here: https://stackoverflow.com/questions/42360139/asp-net-core-return-json-with-status-code – Peska May 19 '23 at 11:01
  • The immediate issue I'm seeing is the controller is executed `async` but your test does not execute the controller with `await`. If you execute the controller method using await, does that change the results? See [How does one test async code using MSTest](https://stackoverflow.com/q/2060692/3092298) for more info. – Greg Burghardt May 22 '23 at 17:57
  • @Peska but when the application it's running, apparently there is some middleware that wraps it under the hood. – Vinicius Andrade May 24 '23 at 00:32

0 Answers0