powermockito.donothing()抛出无指针异常



i正在模拟Objectoutputstream void方法.writeObject((,但它引发了null指针异常。如何使用Mockito/PowerMockito模拟空隙函数。

class

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)

ObjectOutputStreamMock为null。您必须初始化它:

objectOutputStreamMock = Mockito.mock(ObjectOutputStream.class) 

相关内容

  • 没有找到相关文章

最新更新