我正在测试一些旧代码,并尝试模拟超类中的某些行为。奇怪的是,mockito不会触发并返回我的期望值,在某些情况下,它甚至在doReturn行上抛出NullpointerException。以下是相关代码:
类来测试
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];
}
}
测试类
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();
}
}
或者,我将doReturn(20)....替换为
doReturn(20).when(this.spy).read(any(), any(), any());
但是然后我得到了NullPointerException。我看不到哪里出了问题,我们将非常感谢Help。
到目前为止谢谢你
最佳答案
如果您不需要覆盖read
,只需使用this.read
而不是super.read
,您的代码就可以使用。
参见Mockito How to mock only the call of a method of the superclass
NullPointerException的第二个问题:
对于接受原始anyInt()
的参数,您需要使用any()
,而不是int