Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
119 views
in Technique[技术] by (71.8m points)

c# - 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.

question from:https://stackoverflow.com/questions/66048235/unit-test-for-api-controller-in-asp-net-core-3-1-returning-a-wrong-status-code

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...