英文:
How to unit test a Java method which calls a different class's static method
问题
我使用纯Java和Junit。
Class A {
public void tesetMe(arg1, arg2) {
arg3 = getArg3(arg1);
B.staticMethod(arg1, arg2, arg3);
}
}
Class B {
public static void staticMethod(String arg1, String arg2, int arg3) {
//---
}
}
我正在测试Class A的testMe方法。
我想验证B的staticMethod是否以特定的arg1、arg2和arg3值调用。
我不能拥有一个类型为Class B的数据成员。
我可以使用Mockito,但不能使用PowerMock或任何其他库。我没有一个容器,可以在其中注入Class B的实例。我只是有一些普通的Java程序互相调用。
英文:
I use plain Java and Junit.
Class A {
public void tesetMe(arg1, arg2) {
arg3 = getArg3(arg1);
B.staticMethod(arg1, arg2, arg3);
}
Class B {
public static void staticMethod(String arg1, String arg2, int arg3) {
//---
}
}
I am testing Class A's testMe method.
I want to verify if B's staticMethod is called with specific values of arg1, arg2 and arg3.
I cannot have a data member of type Class B.
I can use mockito but not powermock or any other library. I do not have a container where I can inject an instance of Class B. I have this like a plain simple java programs calling each other.
答案1
得分: 1
所以我查了一下,我认为这可以解决你的问题。可以通过调用mockStatic
函数来模拟静态类,以下是一个快速示例:
MockedStatic<StaticClass> x = Mockito.mockStatic(StaticClass.class);
之后,你可以像这样调用所有常规函数:
x.verify(() -> StaticClass.staticFunction("x"));
我找到了这篇Baeldung教程,还找到了一个类似的问题。
希望对你有帮助!
英文:
So I looked this up and I think this can solve your problem. One can mock a static class by calling mockStatic function, here is a quick example:
MockedStatic<StaticClass> x = Mockito.mockStatic(StaticClass.class);
After that, you can call all the usual functons you would on x variable like that:
x.verify(() -> StaticClass.staticFunction("x"));
I found this Baeldung tutorial and also found a similar question.
Hope this helps!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论