Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using PowerMockito to mock method with void return-type: "invalid void parameter"

I am having some trouble trying to unit test java code that at some point calls native methods. Basically, I am trying to use PowerMockito to mock the class that will eventually call native. I was able to mock non-void methods just fine, but I keep getting compilation errors when I try to mock a method of void return type. Here is an example of the code I'm trying to test:

public class ClassThatCallsNative {

    void initObject(ByteBuffer param1, int param2) {
        //calls native
    }

    int getId(int param1) {
        //calls native
    }
}

I have this code in my test class:

PowerMockito.when(mClassThatCallsNative.getId(Mockit.anyInt())).thenReturn(0);

This line of code compiles just fine, however the following line is where I get compilation error:

PowerMockito.when(mClassThatCallsNative.initObject(Mockit.any(ByteBuffer.class), anyInt())).doNothing();

The error message just says invalid void parameter and points to .initObject. Any idea what I am doing wrong?

like image 540
sasfour Avatar asked Sep 10 '14 19:09

sasfour


1 Answers

Since you are trying to mock method which returns void, you simply can't call it inside when() method. This is because PowerMockito.when() methods expects T methodCall but got void, this is the reason for compilation failure. Instead you should use this syntax:

PowerMockito.doNothing().when(mClassThatCallsNative).initObject(any(ByteBuffer.class), anyInt())

any() and anyInt() methods are part of Mockito class.

like image 89
Grigory Avatar answered Nov 12 '22 21:11

Grigory