Description:
I cannot seem to have my stubs or mocks take affect in the class I have under test. I am trying to use the whenNew action so I can mock a return object and then mock a operation on that object with a returned value.
I imagine its something simple I am missing but not seeing it.
SOLUTION: Originally I was running with MockitoRunner.class
and it required being changed to PowerMockRunner.class
. Code below reflects the solution.
Jars on the classpath:
TEST CLASS
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import static org.powermock.api.mockito.PowerMockito.*;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import static org.mockito.Matchers.any;
@RunWith(PowerMockRunner.class)
@PrepareForTest(ClassA.class)
public class ClassATest {
@Test
public void test() throws Exception
{
String[] returnSomeValue = {"PowerMockTest"};
String[] inputValue = {"Test1"};
ClassB mockedClassB = mock(ClassB.class);
whenNew( ClassB.class).withNoArguments().thenReturn( mockedClassB );
when( mockedClassB, "getResult", any(String[].class) ).thenReturn(returnSomeValue);
IClassA classUnderTest = new ClassA();
String[] expectedValue = classUnderTest.runTest(inputValue);
}
}
Class A Implementation
public class ClassA implements IClassA {
@Override
public String[] runTest(String[] inputValues) {
String[] result;
IClassB classB = new ClassB();
result = classB.getResult(inputValues);
return result;
}
}
Since you are using powermock features (@PrepareForTest
, PowerMockito.whenNew
etc.), you have to run your test with the PowerMockRunner.
@RunWith(PowerMockRunner.class)
Because ClassB#geResult is not private, you may also simplify your code and replace
when( mockedClassB, "getResult", any(String[].class) ).thenReturn(someValue);
by
when(mockedClassB.getResult(any(String[].class))).thenReturn(someValue);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With