简体   繁体   English

如何模拟没有返回类型的 class 的 static 方法

[英]how to mock static method of a class with no return type

I need to mock a static method of a class which is also void.我需要模拟 class 的 static 方法,这也是无效的。 So, lets say if my class is.所以,假设我的 class 是。

class Util{
public static void test(){}
}

and my Action class which calls Util's method和我调用 Util 方法的 Action class

class Action{
public void update(){
Util.test();
}

}

My test class is:我的测试 class 是:

class Test{
Action action=new Action();
action.update();

//want to 
}

My question is how can I mock a class and verify if its method gets called Util.test();我的问题是如何模拟 class 并验证其方法是否被调用 Util.test(); how can I put something like:我怎么能把这样的东西:

given(Util.test());//in this case I cannot put willReturn as this has type void given(Util.test());//在这种情况下,我不能放置 willReturn,因为它的类型为 void

You don't;你没有; this causes all sorts of problems.这会导致各种问题。 Instead, either test the final effects of your static method (though it's best if static methods don't have side effects), or replace your call to the static method with a functional interface such as Runnable or Consumer and pass Util::test to the Action constructor.相反,要么测试您的 static 方法的最终效果(尽管最好 static 方法没有副作用),或者替换您对Util::test方法的调用并通过功能性:接口,如RunnableConsumer Action构造函数。

You can use the verify() from Mockito this.您可以使用Mockito中的verify()

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

verify(mockObject, atLeast(2)).someMethod("was called at least twice");
verify(mockObject, times(3)).someMethod("was called exactly three times");

I don't have the context to suggest refactoring your design to get rid of the static method, or whether it is appropriate according to your use case.我没有上下文建议重构您的设计以摆脱 static 方法,或者根据您的用例是否合适。

However, you can mock and verify that static methods have been called, using mockito-inline.但是,您可以使用 mockito-inline 模拟并验证是否调用了 static 个方法。 Here a minimal test that does what you need:这是一个可以满足您需要的最小测试:

@Test
public void actionShouldCallUtilTest() {
    try (MockedStatic<Util> mockedStatic = mockStatic(Util.class)) {
        // given
        Action action = new Action();

        // when
        action.update();

        // then
        mockedStatic.verify(Util::test);
    }
}

Have a look at the MockedStatic documentation for its features.查看MockedStatic文档了解其功能。 https://javadoc.io/static/org.mockito/mockito-core/4.3.1/org/mockito/MockedStatic.html https://javadoc.io/static/org.mockito/mockito-core/4.3.1/org/mockito/MockedStatic.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM