PowerMockito. Mock static method. why does not PowerMockito#stub work?

gstackoverflow picture gstackoverflow · May 12, 2014 · Viewed 8.1k times · Source

I want to mock only one static method in class, all other methods should work like real object.

code:

public class ArrTest {

    public static int myMethod (int arr []) {           
        return 777;
    }
}

test for this method:

public class ArrTestTest {
    @Test
    public void myMethodTest(){        
        PowerMockito.stub(PowerMockito.method(ArrTest.class, "myMethod")).toReturn(0);
        System.out.println(ArrTest.myMethod(null));
    }
}

in output I see 777 but I want to see 0;

What do I wrong?

Answer

Mureinik picture Mureinik · May 12, 2014

Your approach is correct, but you're missing the annotations to make PowerMockito instrument the class, and to use the appropriate test runner:

@PrepareForTest(ArrTest.class)
@RunWith(PowerMockRunner.class)
public class ArrTestTest {
    @Test
    public void myMethodTest(){
        PowerMockito.stub(PowerMockito.method(ArrTest.class, "myMethod")).toReturn(0);
        System.out.println(ArrTest.myMethod(null));
    }
}

EDIT:

To address the followup question in the comments - if you already have a test runner and cannot use PowerMockRunner, you can use the PowerMockRule to achieve the same result:

@PrepareForTest(ArrTest.class)
public class ArrTestTest {

    @Rule
    public PowerMockRule rule = new PowerMockRule();

    @Test
    public void myMethodTest(){
        PowerMockito.stub(PowerMockito.method(ArrTest.class, "myMethod")).toReturn(0);
        System.out.println(ArrTest.myMethod(null));
    }
}