I'm writing a unit test for an API Controller performing delete action.
Here's the Delete Action
public IActionResult DeleteSubGenre(Guid subGenreId)
{
if (!_genreRepo.SubGenreExist(subGenreId))
{
return NotFound();
}
var genreObj = _genreRepo.SubGenre(subGenreId);
if (!_genreRepo.DeleteSubGenre(genreObj))
{
ModelState.AddModelError("", $"Something went wrong when deleting the record {genreObj.Name}");
return StatusCode(500, ModelState);
}
return NoContent();
}
The unit test for this action is written as
[Fact]
public void DeleteSubGenre_Returns_NoContentResult()
{
// Arrange
var subGenreRepositoryMock = new Mock<ISubGenreRepository>();
var subGenreIMapperMock = new MapperConfiguration(config =>
{
config.AddProfile(new MovieMapper());
});
var subGenreMapper = subGenreIMapperMock.CreateMapper();
SubGenresController subGenreApiController = new SubGenresController(subGenreRepositoryMock.Object, mapper: subGenreMapper);
var subGenreDto = new SubGenreDTO()
{
Name = "Adult Content",
DateCreated = DateTime.Parse("15 May 2015"),
Id = Guid.NewGuid(),
GenreId = Guid.NewGuid(),
Genres = new GenreDTO()
};
// Act
var subGenreResult = subGenreApiController.DeleteSubGenre(subGenreDto.Id);
var noContentResult = subGenreResult as NoContentResult;
// Assert
Assert.False(noContentResult.StatusCode is StatusCodes.Status204NoContent);
}
While debugging the test i noticed that subGenreResult
was returning a status code of 404 instead of 204. I can seem to get a hang over it. I'll be glad to get plausible solution to this.
question from:
https://stackoverflow.com/questions/66048235/unit-test-for-api-controller-in-asp-net-core-3-1-returning-a-wrong-status-code 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…