0

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
    Usually, the answer here is that you're testing the wrong thing, and you shouldn't be testing calls to static methods. You should either change how B is organized to make it an instance method, or test the effects that tesetMe is supposed to have, whether it calls staticMethod or not. Commented Jan 8, 2023 at 18:01

1 Answer 1

1

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!

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.