在Spring Boot集成测试中模拟静态方法

huangapple go评论67阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年6月5日 21:30:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76406935.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定