[当我尝试进行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));
我的stacktrace的输出中包含以下内容...
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
您需要稍微更改测试方法如下所示。需要更正]
@Test
void getSingleMovie() throws Exception{
Movies movies = new Movies(1, "Star Wars", "A New Hope");
when(moviesRepository.findById(Mockito.eq(1))).thenReturn(Optional.of(movies));
MvcResult mvcResult = mockMvc.perform(
MockMvcRequestBuilders.get("/movie/1")
.accept(MediaType.APPLICATION_JSON)
).andReturn();
Mockito.verify(moviesRepository).findById(Mockito.eq(1));