在 ASP.NET 网络 api 控制器中为单元测试设置模拟存储库时返回错误请求
Returning a Bad Request while setting up mock repository in an ASP.NET web api controller for a unit test
我正在为我的 ASP.NET 核心网络 API 控制器编写单元测试。
对于一个特定的单元测试,我正在尝试 post 一部电影并检查同名电影是否已经存在,如果存在,则 returns 是一个错误的请求。 API 工作正常,但我在编写单元测试时遇到问题。
我的 post 请求的控制器代码-
[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 设置行,这样 returns 一个错误的请求。?
我用来填充列表以进行测试的函数。
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;
}
感谢您抽出宝贵时间。我是单元测试的新手,所以如果我问的问题太明显了,我深表歉意
要测试这种情况,无论输入是什么,您都可以将模拟设置为 return true
for MovieExists
。
_mockMovieRepository.Setup(r => r.MovieExists(It.IsAny<string>())).ReturnsAsync(true);
所以它只会模拟给定电影已经在你的回购中的情况(不重现存在检查的完全相同的逻辑,这是为了回购测试),从控制器的角度来看就足够了测试。
您的控制器将return BadRequest
按预期正确执行,因此您无需生成虚假结果。
我正在为我的 ASP.NET 核心网络 API 控制器编写单元测试。 对于一个特定的单元测试,我正在尝试 post 一部电影并检查同名电影是否已经存在,如果存在,则 returns 是一个错误的请求。 API 工作正常,但我在编写单元测试时遇到问题。
我的 post 请求的控制器代码-
[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 设置行,这样 returns 一个错误的请求。?
我用来填充列表以进行测试的函数。
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;
}
感谢您抽出宝贵时间。我是单元测试的新手,所以如果我问的问题太明显了,我深表歉意
要测试这种情况,无论输入是什么,您都可以将模拟设置为 return true
for MovieExists
。
_mockMovieRepository.Setup(r => r.MovieExists(It.IsAny<string>())).ReturnsAsync(true);
所以它只会模拟给定电影已经在你的回购中的情况(不重现存在检查的完全相同的逻辑,这是为了回购测试),从控制器的角度来看就足够了测试。
您的控制器将return BadRequest
按预期正确执行,因此您无需生成虚假结果。