javaspring-bootmockitojunit5spring-boot-test

Mock static method in spring boot integration test


I have a sample spring boot application and I am writing test cases using TestRestTemplates.

We have one static class in RestController and we want to mock a static method call. I checked with Mockito.mockStatic, but it is not working.

You can find the source code here


Solution

  • Mockito.mockStatic docs state:

    it is possible to mock static method invocations within the current thread

    When you're calling restTemplate.getForEntity("/test", String.class) you're sending the request within the servlet, which is handled in a separate thread - that's why your static mocking is not working.

    A simple explicit call such as: new SampleController().test() returns "test" as defined in the static mock, so the mechanism is actually working.

    If you want to test only the method and not the whole request handling, you could use the explicit method calling approach. If you want to verify the whole request handling, the suggestion from the comments seems reasonable (proxying the static call through another class, which could be mocked and injected for testing).