英文:
Mock static method in spring boot integration test
问题
我有一个示例的Spring Boot应用程序,我正在使用TestRestTemplates
编写测试用例。
在我们的RestController
中有一个静态类,我们想要模拟一个静态方法的调用。我尝试过使用Mockito.mockStatic
,但它不起作用。
您可以在这里找到源代码。
英文:
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
答案1
得分: 1
Mockito.mockStatic 文档中提到:
> 可以在当前线程内模拟静态方法调用
当您调用restTemplate.getForEntity("/test", String.class)
时,您正在在Servlet内发送请求,该请求在单独的线程中处理 - 这就是为什么您的静态模拟不起作用的原因。
像new SampleController().test()
这样的简单显式调用会返回静态模拟中定义的"test"
,因此该机制确实起作用。
如果您只想测试方法而不是整个请求处理,您可以使用显式方法调用的方法。如果您想验证整个请求处理过程,评论中的建议似乎是合理的(通过另一个类代理静态调用,该类可以用于测试时模拟和注入)。
英文:
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).
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论