【问题标题】:Returning a Bad Request while setting up mock repository in an ASP.NET web api controller for a unit test在 ASP.NET Web api 控制器中为单元测试设置模拟存储库时返回错误请求
【发布时间】:2021-01-27 17:33:07
【问题描述】:

我正在为我的 ASP.NET 核心 Web API 控制器编写单元测试。 对于一个特定的单元测试,我试图发布一部电影并检查是否已经存在同名的电影,如果存在,它会返回一个错误的请求。 API 工作正常,但我在编写单元测试时遇到问题。

我的发布请求的控制器代码-

        [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);
    }

我正在写的测试-

        [Test]
    public async Task GivenAValidMovie_WhenIPostANewMovieWithExistingName_ThenItReturnsbadRequest()
    {
        getMoviesHelper getMoviesHelper = new getMoviesHelper();
        List<TblMovie> movieList = getMoviesHelper.getMovieFromList();
        _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(BadRequest());
        _moviesController = new MoviesController(_mockMovieRepository.Object, _mockMovieMapper.Object);
        var tblMovie = await _moviesController.AddMovie(new MovieForDetailedDto
        {
            AMovieId = 3,
            ATitle = "Big Hero 6",
            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"
        });
        Assert.IsInstanceOf<BadRequestObjectResult>(tblMovie);

    }

不确定我应该如何编写 _mockMovieRepository 设置行以使其返回错误请求。?

我用来填充列表以进行测试的函数。

        public List<TblMovie> getMovieFromList()
    {
        var movies = new List<TblMovie>();
        movies.Add(new TblMovie()
        {
            AMovieId = 2,
            ATitle = "Big Hero 6",
            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"
        });

}

我应该如何继续编写这个函数-

        public TblMovie movieByNameExists(TblMovie tMovie)
    {
        var movies = getMovieFromList();
        foreach (TblMovie tblMovie in movies)
        {
            if (tblMovie.ATitle == tMovie.ATitle)
            {
                //return "movie already exists";
                // How do I return a BAD REQUEST HERE;

            }
        }
        return tMovie;
    }

感谢您的宝贵时间。我对单元测试很陌生,如果我问的东西太明显了,我很抱歉

【问题讨论】:

    标签: c# unit-testing nunit automapper asp.net-core-webapi


    【解决方案1】:

    要测试这种情况,您只需将模拟设置为返回 trueMovieExists,无论输入是什么。

    _mockMovieRepository.Setup(r => r.MovieExists(It.IsAny<string>())).ReturnsAsync(true);
    

    因此,它只会模拟给定电影已经在您的存储库中的情况(不复制与存储库测试完全相同的存在检查逻辑),从控制器测试的角度来看,这已经足够了。

    您的控制器将按预期正确返回BadRequest,因此您无需生成虚假结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-01-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-01
      • 1970-01-01
      相关资源
      最近更新 更多