简体   繁体   中英

Unit test for API Controller in ASP.NET Core 3.1 returning a wrong status code

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.

You have to setup your mock to drive the execution of your test case.

For example if you want to go through this line: if (._genreRepo.SubGenreExist(subGenreId))

then you have to setup the following mock behaviour:

subGenreRepositoryMock.Setup(repo => repo.SubGenreExist(It.IsAny<Guid>)).Returns(true);

To reach this line: return NoContent(); you might need to setup the other two methods as well to drive your test case.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM