Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Mockito spy in one class to Call static method from another class

Trying to use Mockito's spy function for my JUnit test. I originally had a Class:

public class App1 { 
    public String method1() {
        sayHello();
    }

    public sayHello() {
        Systems.out.println("Hello");
    }
}

Everything in my test class was working correctly with mockito spy on above class:

@Test(expected = IOException.class)
public void testMethod1Failure(){   
    App1 a1 = spy(App1);
    doThrow(IOException.class).when(a1).sayHello();

    a1.method1();
}

But after that i had to switch things around and take sayHello() method into another class to be used as static method:

public class App1 { 
    public String method1() {
        App2.sayHello();
    }
}

public class App2 { 
    public static void sayHello() {
        Systems.out.println("Hello");
    }
}

After this change, my original JUnit testcase is broken and i am unsure how i can use Mockito spy to start App1 that calls the external App2 static method... does anyone know how i can do it? Thanks in advance

like image 499
R.C Avatar asked Apr 04 '17 00:04

R.C


People also ask

Can we use spy for static methods?

Spies allow us to partially mock. This means that we can mock a part of the object but allow for real method calls for the rest of the object. Here, we are creating a wrapper method that calls the static method. Now, in our regularMethod, we can call this wrapper class instead of calling the static class directly.

Can we mock static methods using Mockito?

Mockito allows us to create mock objects. Since static method belongs to the class, there is no way in Mockito to mock static methods. However, we can use PowerMock along with Mockito framework to mock static methods.

How do you verify a static method is called in Mockito?

To define mock behavior and to verify static method invocations, use the MockedStatic reference returned from the Mockito. mockStatic() method. It is necessary to call ScopedMock. close() method to release the static mock once it has been used and is no longer needed.

Can static classes be mocked?

The powerful capabilities of the feature-rich JustMock framework allow you to mock static classes and calls to static members like methods and properties, set expectations and verify results. This feature is a part of the fastest, most flexible and complete mocking tool for crafting unit tests.


1 Answers

Mockito does not support mocking static code. Here are some ways to handle it:

  • Use PowerMockito or similar framework as suggested here: Mocking static methods with Mockito.
  • Refactor your code converting static method back to an instance method. As you've found static methods are not easy to Unit test.
  • If it's inexpensive to execute actual static method in question then just call it.
like image 155
VinPro Avatar answered Sep 23 '22 19:09

VinPro