Spring Boot 单元测试 @MockBean 模拟依赖注入

Spring Boot 单元测试 About 1,336 words

@MockBean

使用@MockBean标识注入的Component是模拟的,不会运行真实的组件逻辑,需要自己给定假设的返回值。

假设返回值

使用given()指定Service层调用的方法和参数。

使用willReturn()指定Service层调用的方法的返回值。

BDDMockito.given(helloService.sayHello(1))
        .willReturn(Response.builder().msg("response msg").build());

示例代码

示例中@MockBean标注的HelloService组件,真实对象是一个Mock出来的实现类,并非自己写的HelloServiceImpl这种。

配合given()willReturn()MockMvcandExpect(),进行单元测试。

@WebMvcTest(HiController.class)
class HiControllerTests {

    @Autowired
    MockMvc mockMvc;

    @MockBean
    HelloService helloService;

    @Test
    @DisplayName("测试 GetMapping 接口")
    void testGetMappingWithMockMvc() throws Exception {
        BDDMockito.given(helloService.sayHello(1))
                .willReturn(Response.builder().msg("response msg").build());

        mockMvc.perform(MockMvcRequestBuilders.get("/hi")
                        .header("token", "test-token")
                        .param("username", "test-username")
                )
                .andExpect(MockMvcResultMatchers.status().isOk())
                .andDo(MockMvcResultHandlers.print())
                .andExpect(MockMvcResultMatchers.content().string(containsString("msg")))
                .andReturn();
    }

}

参考

https://docs.spring.io/spring-boot/docs/current/reference/html/features.html#features.testing.spring-boot-applications.with-mock-environment

Views: 1,940 · Posted: 2022-10-15

————        END        ————

Give me a Star, Thanks:)

https://github.com/fendoudebb/LiteNote

扫描下方二维码关注公众号和小程序↓↓↓

扫描下方二维码关注公众号和小程序↓↓↓


Today On History
Browsing Refresh