Testing class with Protected Constructor w/ PowerMock and Mockito
-
26-05-2021 - |
Question
I have the following class to test:
public abstract class Challenge {
protected int id;
protected String name;
protected String question;
protected Challenge(){}
public String[] toStrings(){
String[] s = {Integer.toString(id), name, question};
return s;
}
...
But using this test:
@Test
public void testToStrings() throws Exception{
String[] expectedResult1 = new String[]{"1", "a", "b"};
String[] obtainedResult1 = null;
Challenge challengeMock = PowerMockito.mock(Challenge.class);
challengeMock.id = 1;
challengeMock.name = "a";
challengeMock.question = "b";
obtainedResult1 = challengeMock.toStrings();
Assert.assertEquals(expectedResult1[0], obtainedResult1[0]);
Assert.assertEquals(expectedResult1[1], obtainedResult1[1]);
Assert.assertEquals(expectedResult1[2], obtainedResult1[2]);
}
I get a NullPointerException due to "obtainedResult1 = challengeMock.toStrings();" that returns null.
I use PowerMock + Mockito running in Robolectric with rule(becouse its an Android project).
@Rule
public PowerMockRule rule = new PowerMockRule();
Where is the problem?
Solution
You don't need PowerMock for this; a Mockito mock will be just fine. But normally, a mock has no functionality in its methods, which is why toStrings()
isn't returning the value that you expect. To change this, you need the CALLS_REAL_METHODS
default answer.
So my recommendation would be to change the line where you create the mock (the third non-empty line of testToStrings
) to something like this.
Challenge challengeMock = Mockito.mock(Challenge.class, Mockito.CALLS_REAL_METHODS );
I have tested this, and your test passes if you make this change.