1

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.

Matt
  • 11
  • 2
  • AFIK running test with @RunWith(SpringRunner.class) would not instantiate Mockito. you probably need something like MockitoAnnotations.initMocks(this); call in the setup/before test method. also check this out https://stackoverflow.com/questions/48589893/autowire-mockmvc-spring-data-rest – Vlad Ulshin May 02 '23 at 00:11
  • I changed the comment to an answer instead. – 1615903 May 02 '23 at 10:18
  • 2
    Does this answer your question? [Why are my mocked methods not called when executing a unit test?](https://stackoverflow.com/questions/74027324/why-are-my-mocked-methods-not-called-when-executing-a-unit-test) (definitely a dupe) – knittl May 02 '23 at 10:52

2 Answers2

1

TestService in your controller is not a spring bean, you are instantiating it directly:

public TestService testService = new testServiceImpl();. 

Autowire it instead.

1615903
  • 32,635
  • 12
  • 70
  • 99
0

Autowiring the TestService solved my problem.

Matt
  • 11
  • 2
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 03 '23 at 06:05