Spring Boot 控制器 HTTP Post 请求测试返回一个具有空主体的 MockHttpServletResponse,尽管有 200 状态代码

问题描述 投票:0回答:1

运行测试时,如果控制器调用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!");
    }
}
java spring-boot post mocking mockmvc
1个回答
0
投票

如果我们查看

@WebMvcTest
的定义,它包括
@ExtendWith(SpringExtension.class)
@AutoConfigureMockMvc
,因此可以将它们删除。

使用没有值的

@WebMvcTest
,需要模拟Web层使用的所有依赖项,否则测试将因未解决的依赖项而失败。

要将测试上下文范围缩小到被测控制器,请使用

@WebMvcTest(NotesController.class)
注释您的测试类,而不使用其他任何内容。然后只需要模拟被测控制器的依赖关系。

答案已使用问题代码和 Spring Boot 3.3.2 进行验证。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.