Kev
Kev

Reputation: 109

How do you test for NotFound() in ASP.Net Core MVC

Hi I am trying to write Unit Tests for my controller, this is my fist test I have written, well, trying to write.

In my controller I have the method -

public IActionResult Details(int id)
{
    var centre = _centreRepository.GetCentreById(id);

    if (centre == null)
    {
       return NotFound();
    }

    return View(Centre);
}

I am trying to write a test so that it passes when NotFound() is returned.

For my test I have -

 [Test]
 public void TestVaccinationCentreDetailsView()
 {
     var centrerepository = new Mock<ICentreRepository>();

     var controller = new CentreController(centrerepository.Object);

      var result = controller.Details(99);
      Assert.AreEqual(404, result.StatusCode);
}

When run result returns Microsoft.AspNetCore.Mvc.NotFoundResult object, which has status code of 404. result.StatusCode does not exist.

I am confused.

I am using .Net 5, ASP.Net core MVC 5.

Can anyone help please?

Thank you.

Upvotes: 3

Views: 2621

Answers (3)

tnJed
tnJed

Reputation: 917

I tried verifying or casting to type NotFoundResult and NotFoundObjectResult but was still getting null. The result I was getting was of type StatusCodeResult, but I did need to cast to that in order to make an assertion. The final result was this:

[Fact]
public async void TestGetStuffNotFound()
{
    mockContext.Setup(x => x.GetStuff()).ReturnsAsync(new List<Stuff>());
    var result = await controller.GetAllStuff(mockContext.Object) as StatusCodeResult;
    Assert.Equal(404, result?.StatusCode);
}

Upvotes: 0

Alexander
Alexander

Reputation: 9632

It is enough to just test if the result is of NotFoundResult type

var result = controller.Details(99);

//I prefer this one
Assert.IsInstanceOf<NotFoundResult>(result);
//other possible solution
Assert.IsTrue(result is NotFoundResult);

Upvotes: 2

Nkosi
Nkosi

Reputation: 247018

The controller action is returning an abstraction. ie IActionResult

Cast the result in the test to the expected type and assert on that

[Test]
public void TestVaccinationCentreDetailsView() {
    //Arrange
    var centrerepository = new Mock<ICentreRepository>();

    var controller = new CentreController(centrerepository.Object);

    //Act
    var result = controller.Details(99) as NotFoundResult; //<-- CAST HERE

    //Assert
    Assert.IsNotNull(result);
    Assert.AreEqual(404, result.StatusCode);
}

Upvotes: 2

Related Questions