单元测试期间 Web API 控制器 returns 中的映射器函数为空

Mapper function in Web API Controller returns null during unit testing

我正在制作 ASP.NET 核心网站 api 并且我已经使用了 Entity Framework 核心。我正在尝试使用 N-Unit 对控制器进行单元测试 我在嘲笑映射器和存储库。 API 工作正常,我什至创建了前端或 API,但我在单元测试方面遇到问题。

控制器代码-

[AllowAnonymous]
    [HttpGet("{id}")]
    public async Task<IActionResult> GetMovie(int id)
    {
        var movie = await _repo.GetMovie(id);
        if (movie == null)
        {
            return BadRequest("Object with Id not found");
        }
        var movieToReturn = _mapper.Map<MovieForDetailedDto>(movie);
        return Ok(movieToReturn);
    }

    [AllowAnonymous]
    [HttpPost()]
    public async Task<IActionResult> AddMovie(MovieForDetailedDto movieForDetailedDto)
    { 
        if (await _repo.MovieExists(movieForDetailedDto.ATitle))
            return BadRequest("movie already exists");

        else if(!ModelState.IsValid || movieForDetailedDto.ATitle == null || movieForDetailedDto.APrice == null || movieForDetailedDto.AMovieDescription ==null)
        {
            return BadRequest("movie details not valid");
        }

        var movieToCreate = _mapper.Map<TblMovie>(movieForDetailedDto);

        var createdMovie = await _repo.AddMovie(movieToCreate);

        return Ok(createdMovie);
    }

在我所有的函数中,在我将 DTO 映射到模型的行中,行 returns 在单元测试期间是一个空对象,但它们在单元测试之外工作正常。

我的控制器单元测试代码-

[TestFixture]
public class MoviesControllerTests
{
    private Mock<IMovieRepository> _mockMovieRepository;
    private Mock<IMapper> _mockMovieMapper;
    private MoviesController _moviesController;
    [Test]
    public async Task CallGetRequest_WhenCalledWithId_ReturnsTheMovieWithTheSameId()
    {
        getMoviesHelper getMoviesHelper = new getMoviesHelper();
        List<TblMovie> movieList = getMoviesHelper.getMovieFromList();
        var movie = getMoviesHelper.movieById(3);
        _mockMovieRepository = new Mock<IMovieRepository>();
        _mockMovieMapper = new Mock<IMapper>();
        _mockMovieMapper.Setup(mapper => mapper.Map<TblMovie>(It.IsAny<MovieForDetailedDto>()))
            .Returns(getMoviesHelper.movieById(3));
        _mockMovieRepository.Setup(repo => repo.GetMovie(3))
                .ReturnsAsync(getMoviesHelper.movieById(3));
        _moviesController = new MoviesController(_mockMovieRepository.Object, _mockMovieMapper.Object);
        var tblMovie = await _moviesController.GetMovie(3);
        var okResult = tblMovie as OkObjectResult;
        //Assert.AreEqual(200, okResult.StatusCode);
        Assert.NotNull(tblMovie);
        Assert.IsAssignableFrom<OkObjectResult>(tblMovie);
        var result = ((OkObjectResult)tblMovie).Value;
        var resultValue = ((OkObjectResult)tblMovie).Value as TblMovie;
        Assert.AreEqual(resultValue.ATitle,"Raging Bull");
        Assert.NotNull(result);
        Assert.IsAssignableFrom<TblOrder>(result);
    }

    [Test]
    public async Task GivenAValidMovie_WhenIPostANewMovie_ThenItReturnsOkWithResponse()
    {
        _mockMovieRepository = new Mock<IMovieRepository>();
        _mockMovieMapper = new Mock<IMapper>();
        _mockMovieMapper.Setup(mapper => mapper.Map<TblMovie>(It.IsAny<MovieForDetailedDto>()))
            .Returns(new TblMovie());
        _mockMovieRepository.Setup(repo => repo.AddMovie(It.IsAny<TblMovie>()))
            .ReturnsAsync((TblMovie movie) => movie);

        _moviesController = new MoviesController(_mockMovieRepository.Object, _mockMovieMapper.Object);
        var tblMovie = await _moviesController.AddMovie(new MovieForDetailedDto
        {
            AMovieId = 55,
            ATitle = "redemption",
            AMovieDescription = "An action comedy adventure about brilliant robotics prodigy Hiro Hamada, who finds himself in the grips of a criminal plot that threatens to destroy the fast-paced, high-tech city of San Fransokyo. With the help of his closest companion-a robot named Baymax-Hiro joins forces with a reluctant team of first-time crime fighters on a mission to save their city.",
            ADuration = "105 min",
            APrice = "10",
            APurchasePrice = "25",
            ARating = 5,
            AImageLink = "http://upload.wikimedia.org/wikipedia/en/4/4b/Big_Hero_6_%28film%29_poster.jpg",
            ATrailerLink = "//www.youtube.com/embed/z3biFxZIJOQ",
            AGenre = "Comedy",
            AWideImage = "https://github.com/tushar23091998/MovieRentalApp-FrontEnd/blob/master/src/app/images/bighero6.jpg?raw=true"
        });
        var okResult = tblMovie as OkObjectResult;
        Assert.AreEqual(200, okResult.StatusCode);
        Assert.NotNull(okResult);
        Assert.IsAssignableFrom<OkObjectResult>(tblMovie);
        var result = ((OkObjectResult)tblMovie).Value;
        Assert.NotNull(result);
        Assert.IsAssignableFrom<TblMovie>(result);
    }

在这两个测试用例中,甚至在其他测试用例中,repo 设置工作正常,但是在定义控制器之后,当我调用控制器函数来获取值时,我在调试中发现控制器代码中的映射器行returns 空。

我不确定现在如何设置 mockmapper 以及我应该如何传递值。

调试输出 -

当使用 AutoMapper 时,我们在单元测试中所做的不是模拟它,而是初始化它,如下所述:https://kenbonny.net/2018/01/15/injecting-automapper-profiles-in-tests/ 我看到这样做的缺点是,您的测试可能由于映射问题而失败,并且没有严格测试该方法。 鉴于您的示例,您的设置不正确。 对于 get 方法测试,您应该为 TblMovie 设置 return MovieForDetailedDto,但您正在做相反的事情:

_mockMovieMapper.Setup(mapper => mapper.Map<TblMovie>(It.IsAny<MovieForDetailedDto>())).Returns(getMoviesHelper.movieById(3));

应该是这样的:

var expectedMovieDto = new MovieForDetailedDto(){//insert values here}
_mockMovieMapper.Setup(mapper => mapper.Map<MovieForDetailedDto>(It.IsAny<TblMovie>())).Returns(expectedMovieDto);

对于 POST 方法,您将其设置为 return 一个新的 TblMovie(因此所有属性都设置为其默认值)

_mockMovieMapper.Setup(mapper => mapper.Map<TblMovie>(It.IsAny<MovieForDetailedDto>())) .Returns(new TblMovie());
        

应该是:

var expectedMovie = new TblMovie()
{
ADuration = "some value",
AGenre = "some value"
//other }

_mockMovieMapper.Setup(mapper => mapper.Map<TblMovie>(It.IsAny<MovieForDetailedDto>())).Returns(expectedMovie);