gpt4 book ai didi

java - Mockito 不会在 super 方法上触发 doReturn

转载 作者:行者123 更新时间:2023-12-02 06:02:15 25 4
gpt4 key购买 nike

我正在测试一些遗留代码并尝试模拟父类(super class)中的某些行为。奇怪的是,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];
}
}

带有测试的类(class)

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。我看不出哪里出了问题,非常感谢您的帮助。

到目前为止谢谢你

最佳答案

如果您不需要重写read,只需使用this.read而不是super.read,您的代码就可以工作。

参见Mockito How to mock only the call of a method of the superclass

NullPointerException 的第二个问题:对于接受原始 int

的参数,您需要使用 anyInt(),而不是 any()

关于java - Mockito 不会在 super 方法上触发 doReturn,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60721053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com