Antei
Antei

Reputation: 39

How to unit test a Java method which calls a different class's static method

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.

Upvotes: 0

Views: 1095

Answers (1)

Mark Ardman
Mark Ardman

Reputation: 35

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!

Upvotes: 1

Related Questions