I have working Spring Boot app and want to test the API endpoints. I am running my test with SpringRunner, using @MockBean annotation and doReturn...when. But still, I am getting the original reponse and the mocking has no effect.
Code from my app:
public TestService testService = new testServiceImpl();
@GetMapping("/test")
public String test() {
return testService.greet();
}
TestService:
@Service
public class TestServiceImpl implements TestService {
public String greet() {
return "Hello";
}
}
And my test 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")));
}
}
This test fails as I get Hello as a response.
I have tried if the mocking works inside the test and it does.
assert testService.greet().equals("Hi");
So the problem must be in using it outside my test class.