从 3.4.0 版本开始,Mockito 已经可以支持测试静态方法了。
Mocking static methods (since 3.4.0)
When using the inline mock maker, it is possible to mock static method invocations within the current thread and a user-defined scope. This way, Mockito assures that concurrently and sequentially running tests do not interfere. To make sure a static mock remains temporary, it is recommended to define the scope within a try-with-resources construct. In the following example, the Foo type’s static method would return foo unless mocked:
assertEquals(“foo”, Foo.method());
try (MockedStatic mocked = mockStatic(Foo.class)) {
mocked.when(Foo::method).thenReturn(“bar”);
assertEquals(“bar”, Foo.method());
mocked.verify(Foo::method);
}
assertEquals(“foo”, Foo.method());
Due to the defined scope of the static mock, it returns to its original behavior once the scope is released. To define mock behavior and to verify static method invocations, use the MockedStatic that is returned.