【发布时间】:2020-03-14 22:44:58
【问题描述】:
当我尝试 findbyid 测试时,我试图在我的控制器上运行测试,但我不断收到 404,但我不确定为什么。
这是来自我的控制器的方法
@CrossOrigin
@GetMapping(path="/movie/{id}")
public @ResponseBody Movies getMovie(@PathVariable Integer id){
return moviesRepository.findById(id)
.orElseThrow(() -> new ResponseStatusException(
HttpStatus.NOT_FOUND, "Movie not found"
) );
}
这就是测试。
@Test
void getSingleMovie() throws Exception{
Movies movies = new Movies(1, "Star Wars", "A New Hope");
when(moviesController.getMovie(1)).thenReturn(movies);
MvcResult mvcResult = mockMvc.perform(
MockMvcRequestBuilders.get("/movies/1")
.accept(MediaType.APPLICATION_JSON)
).andReturn();
Mockito.verify(moviesRepository).findAllById(Collections.singleton(1));
我的堆栈跟踪的输出包含以下内容...
MockHttpServletResponse:
Status = 404
Error message = Movies not found
Headers = [Vary:"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers"]
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
java.lang.AssertionError: Response header 'Access-Control-Allow-Origin' expected:<*> but was:<null>
Expected :*
Actual :null
【问题讨论】:
-
控制器有请求映射吗?
-
您的方法与
/movie/{id}映射,但在测试中您使用的是/movies/1(它有多余的字符s)。 -
是的,尝试在
/movie/1上更改测试中的 URL。 IE。MockMvcRequestBuilders.get("/movie/1"). -
/movies/1url 错误,在/movie/1上更改它。 -
这是因为控制器调用了
findById方法,但在测试中您正在检查的是被称为findAllById存储库方法。
标签: spring-boot mockito mockmvc