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);
}
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.