如何对调用不同类的静态方法的Java方法进行单元测试

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

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&lt;StaticClass&gt; x = Mockito.mockStatic(StaticClass.class);

After that, you can call all the usual functons you would on x variable like that:

x.verify(() -&gt; StaticClass.staticFunction(&quot;x&quot;));

I found this Baeldung tutorial and also found a similar question.
Hope this helps!

huangapple
  • 本文由 发表于 2023年1月9日 00:17:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75049382.html
匿名

发表评论

匿名网友

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

确定