我正在使用C#,Net Core 2.2和XUnit测试框架。
将无效的模型传递给我的Net Core WebApi会返回错误的请求。 在Postman中进行了测试并可以正常工作,但是当我尝试对其进行测试时,我传递了一个Invalid模型,而ModelState始终有效,那么该如何解决呢?
[Route("apia/[controller]")]
[ApiController]
public class MoviesController : ControllerBase
{
private readonly IMovieRepository _movieRepository;
public MoviesController(IMovieRepository movieRepository)
{
_movieRepository = movieRepository;
}
// GET apia/movies
[HttpGet]
public IActionResult Search([FromBody] MovieFilters filters)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
return Ok(_movieRepository.Search(filters));
}
}
这是具有一些必需属性的模型:
public class MovieFilters
{
[Required]
public virtual string Title { get; set; }
[Required]
public virtual int? YearOfRelease { get; set; }
[Required]
public virtual string Genre { get; set; }
}
失败的Test导致ModelState始终为true:
public class MoviesControllerTest: IClassFixture<MovieSeedDataFixture>
{
private readonly MovieFilters _filters;
private readonly MoviesController _controller;
public MoviesControllerTest(MovieSeedDataFixture fixture)
{
var repository = new MovieRepository(fixture.MovieContext);
_controller = new MoviesController(repository);
}
[Fact]
public void Search_EmptyParametersPassed_ReturnsError400()
{
// Act
var result = _controller.Search(new MovieFilters());
// Assert
Assert.IsType<BadRequestObjectResult>(result);
}
}
谢谢
答案 0 :(得分:0)
谢谢,我进行了一些更改,现在可以通过在控制器中手动添加ModelState错误来更好地工作,不确定是否有更好的方法,但是还是可以的。
因此将此行添加到代码中
_controller.ModelState.AddModelError("Title", "Required");
这又是完整的代码:
[Fact]
public void Search_EmptyParametersPassed_ReturnsError400()
{
// Act
_controller.ModelState.AddModelError("Title", "Required");
var result = _controller.Search(new MovieFilters());
// Assert
Assert.IsType<BadRequestObjectResult>(result);
}