运行测试时,如果控制器调用notesService.save(),则不会返回任何数据。它只是返回一个状态 = 200、错误消息 = null 和正文 =(只是空格)的 MockHttpServletResponse。
如果直接从Controller类返回Note对象,它会返回一个JSON对象,但是当使用notesService.save()时它需要起作用。
@WebMvcTest
@ExtendWith(SpringExtension.class)
@AutoConfigureMockMvc
public class NotesControllerTest {
@MockBean
private NotesService notesService;
@Autowired
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@Test
public void testSave() throws Exception {
Note noteToCreate = new Note(null, "Sample Note", "Hello, World!");
Note createdNote = new Note(1L, "Sample Note", "Hello, World!");
when(notesService.save(noteToCreate)).thenReturn(createdNote);
ResultActions response = mockMvc.perform( post("/api/notes")
.contentType(MediaType.APPLICATION_JSON)
.content(objectMapper.writeValueAsString(noteToCreate))
);
response.andDo(print())
.andExpect(MockMvcResultMatchers.status().isOk());
}
}
@RestController
@RequestMapping("/api/notes")
public class NotesController {
@Autowired
private NotesService notesService;
@PostMapping
public Note save (@RequestBody Note note ){
return notesService.save(note);
}
}
@Service
public class NotesService {
public Note save(Note note){
return new Note(1L, "Sample Note", "Hello, World!");
}
}
如果我们查看
@WebMvcTest
的定义,它包括@ExtendWith(SpringExtension.class)
和@AutoConfigureMockMvc
,因此可以将它们删除。
使用没有值的
@WebMvcTest
,需要模拟Web层使用的所有依赖项,否则测试将因未解决的依赖项而失败。
要将测试上下文范围缩小到被测控制器,请使用
@WebMvcTest(NotesController.class)
注释您的测试类,而不使用其他任何内容。然后只需要模拟被测控制器的依赖关系。
答案已使用问题代码和 Spring Boot 3.3.2 进行验证。