我在嘲笑ObjectOutputStream无效方法.writeObject(),但是它抛出空指针异常。 如何使用Mockito / PowerMockito模拟void函数。
班级
public class SomeClass {
public void someMethod() {
//something
OtherClass Obj = new OtherClass();
try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos)) {
oos.writeObject(obj);
// do something
} catch (IOException e) {
//do something
}
//something
}
}
测试类
@RunWith(PowerMockRunner.class)
@PrepareForTest({
SomeClass.class
})
public class SomeClassTest {
@Mock
private ByteArrayOutputStream byteArrayOutputStreamMock;
@Mock
private ObjectOutputStream objectOutputStreamMock;
@Test
public void testSomething() {
MockitoAnnotations.initMocks(this);
PowerMockito.whenNew(ByteArrayOutputStream.class).withNoArguments().thenReturn(byteArrayOutputStreamMock);
PowerMockito.whenNew(ObjectOutputStream.class).withArguments(byteArrayOutputStreamMock).thenReturn(objectOutputStreamMock);
OtherClass otherClass = new OtherClass();
Mockito.doNothing().when(objectOutputStreamMock).writeObject(otherClass); //This throw null pointer exception.
// more code
}
}
Stacktrace
java.lang.NullPointerException
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1108)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
答案 0 :(得分:-1)
objectOutputStreamMock为空。您必须对其进行初始化:
objectOutputStreamMock = Mockito.mock(ObjectOutputStream.class)