[英]NullPointerException when Mockito mocking ObjectOutputStream.writeObject?
I'm writing a jUnit test, checking what a class writes to ObjectOutputStream. 我正在编写一个jUnit测试,检查类将什么写入ObjectOutputStream。
Specifically, I'm checking that a class is calling writeObject with a certain type: 具体来说,我正在检查一个类是否正在以某种类型调用writeObject:
ObjectOutputStream out = mock(ObjectOutputStream.class);
out.writeObject(new Something());
verify(out).writeObject(isA(Something.class));
But Java is complaining of a NullPointerException inside of writeObject
. 但是Java抱怨
writeObject
内部存在NullPointerException。
What do I need to stub to fix this? 我需要存根解决此问题吗?
This isn't possible with Mockito. Mockito无法做到这一点。 According to the ObjectOutputStream javadocs , the
writeOutput
method is final: 根据ObjectOutputStream javadocs ,
writeOutput
方法是最终的:
public final void writeObject(Object obj) throws IOException
Internally, Mockito actually mocks these objects by creating a Proxy , which dynamically overrides ObjectOutputStream. 在内部,Mockito实际上通过创建Proxy来模拟这些对象,该Proxy动态覆盖ObjectOutputStream。 Because the
writeObject
method is final, though, you aren't able to override or mock it and Java calls the original. 但是,由于
writeObject
方法是最终的,因此您无法覆盖或模拟它,而Java会调用原始方法。 This is listed as one of the limitations of Mockito . 这被列为Mockito的限制之一 。
Though you may be able to verify against writeObjectOverride
, your better bet is actually to refactor your code to use the interface ObjectOutput instead of ObjectOutputStream directly. 尽管您可以针对
writeObjectOverride
进行验证,但更好的选择实际上是重构代码,以直接使用ObjectOutput接口而不是ObjectOutputStream接口。 ObjectOutputStream implements ObjectOutput, and Mockito can mock any method of an interface. ObjectOutputStream实现ObjectOutput,而Mockito可以模拟接口的任何方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.