0

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

Nitin
  • 2,701
  • 2
  • 30
  • 60
  • This could be difficult as Mockito / PowerMock and SpringBootTests are quite different on conceptual level. I would try to mock the `static` call per PowerMock and then integrate PowerMock and SprintBootTest as in https://stackoverflow.com/questions/39277036/cannot-use-powermockrunner-with-springboottest – Michal Jun 05 '23 at 14:43
  • 3
    The easiest (and most clean) way of handling this would be to hide the static call in a service, inject the service into the controller and mock that service instead. – Michal Jun 05 '23 at 14:45

1 Answers1

1

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).

Jonasz
  • 1,617
  • 1
  • 13
  • 19