java Sping Boot Mockito @MockBean不会更改返回值[重复]

mspsb9vt  于 2023-05-05  发布在  Java
关注(0)|答案(2)|浏览(114)

此问题已在此处有答案

Why are my mocked methods not called when executing a unit test?(1个答案)
昨天关门了。
我有工作的Sping Boot 应用程序,并希望测试API端点。我正在使用SpringRunner运行我的测试,使用@MockBean注解和doReturn... when。但尽管如此,我还是得到了最初的回应,嘲笑没有任何效果。
我的app代码:

public TestService testService = new testServiceImpl();

@GetMapping("/test")
    public String test() {
        return testService.greet();
    }

测试服务:

@Service
public class TestServiceImpl implements TestService {
    public String greet() {
        return "Hello";
    }
}

我的测试app:

@RunWith(SpringRunner.class)
@WebMvcTest(ExampleApplication.class)
class ExampleApplicationTests {
    @Autowired
    MockMvc mockMvc;

    @MockBean
    private TestServiceImpl testService;

    @Test
    void test() throws Exception{
        doReturn("Hi").when(testService).greet();

        mockMvc.perform(MockMvcRequestBuilders
                .get("/test")
                .contentType(MediaType.APPLICATION_JSON))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$", notNullValue()))
                .andExpect(jsonPath("$", is("Hi")));
    }

}

此测试失败,因为我收到Hello作为响应。
我试过如果嘲笑工作在测试和它做。

assert testService.greet().equals("Hi");

所以问题一定是在我的测试类之外使用它。

oug3syen

oug3syen1#

控制器中的TestService不是spring bean,您直接示例化它:

public TestService testService = new testServiceImpl();.

自动连接。

4si2a6ki

4si2a6ki2#

自动配置TestService解决了我的问题。

相关问题