Using PowerMockito to model a method using void return-type: "invalid void parameter"

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

 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, but the following line contains a compilation error:

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

The error message simply indicates an invalid void parameter and points to .initObject. Any idea what I'm doing wrong?

+5
source share
3 answers

For void methods you need to use below

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

0
source

I thought what the problem was, finally. Turns out I need an instance of the ClassThatCallsNative class to mock its methods. What happened before is that the object was initialized inside the constructor call, but when I created another constructor that takes ClassThatCallsNative as a parameter, and set your instance for it instead, everything works fine.

Anyway, thanks!

0
source

Since you are trying to mock a method that returns void, you simply cannot call it inside when () the method. This is because PowerMockito.when () methods assume T methodCall, but they become invalid and this causes compilation to fail. Instead, you should use this syntax:

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

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

0
source

Source: https://habr.com/ru/post/1202273/


All Articles