I am testing some legacy code and trying to mock some behavior in the superclass. Strangely mockito does not trigger and return my expected value, in some cases, it even throws a NullpointerException on the doReturn line. Here is the relevant code:
class to test
package mypackage;
import java.io.IOException;
import java.io.InputStream;
import java.io.PushbackInputStream;
public abstract class MyClass extends PushbackInputStream
{
public MyClass(InputStream in)
{
super(in, 20);
}
protected final void checkIaikPkcs7() throws IOException
{
byte[] buffer = getInstantiatedByteArray(20);
if (super.read(buffer, 0, buffer.length) != buffer.length)
{
throw new IOException("unable to read needed data");
}
...
}
protected byte[] getInstantiatedByteArray(int size)
{
return new byte[size];
}
}
class with tests
public class MyClassTest
{
private MyClass spy;
private InputStream inputStreamMock;
@Before
public void setUp() throws Exception
{
this.inputStreamMock = mock(InputStream.class);
this.spy = spy(new MyObjectClassExtendingMyClass(inputStreamMock));
}
@After
public void tearDown() throws Exception
{
this.spy = null;
this.inputStreamMock = null;
}
@Test
public void testCheckIaikPkcs7() throws IOException
{
//assure that read is called with exactly the same parameters in mock and implementation
byte[] byteArray = new byte[20];
doReturn(byteArray).when(this.spy).getInstantiatedByteArray(20);
// want 20 returned, but the Test returns 0 (propably not recognizing this line)
doReturn(20).when(this.spy).read(byteArray, 0, byteArray.length);
this.spy.checkIaikPkcs7();
}
}
alternatively, I replaced the doReturn(20).... with
doReturn(20).when(this.spy).read(any(), any(), any());
but then I get a NullPointerException. I cannot see where I went wrong and Help would be realy appreciated.
Thank you so far
If you don't need to override read
, just use this.read
instead of super.read
and your code will work.
See Mockito How to mock only the call of a method of the superclass
Second problem with NullPointerException:
You need to use anyInt()
, not any()
for params that accept primitive int