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.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With