1

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.

1
  • 1
    It seems that you have forgotten to mock _genRepo's SubGenreExist method. Commented Feb 4, 2021 at 15:05

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I noticed that I didn't set up the mock behaviour for all the methods in the delete actions. I tried your suggestion and it worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.