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?

3
  • 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: stackoverflow.com/questions/42360139/… Commented May 19, 2023 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 for more info. Commented May 22, 2023 at 17:57
  • @Peska but when the application it's running, apparently there is some middleware that wraps it under the hood. Commented May 24, 2023 at 0:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.