Question

I'm writing a jUnit test, checking what a class writes to ObjectOutputStream.

Specifically, I'm checking that a class is calling writeObject with a certain type:

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.

What do I need to stub to fix this?

Was it helpful?

Solution

This isn't possible with Mockito. According to the ObjectOutputStream javadocs, the writeOutput method is final:

public final void writeObject(Object obj) throws IOException

Internally, Mockito actually mocks these objects by creating a Proxy, which dynamically overrides ObjectOutputStream. Because the writeObject method is final, though, you aren't able to override or mock it and Java calls the original. This is listed as one of the limitations of 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. ObjectOutputStream implements ObjectOutput, and Mockito can mock any method of an interface.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top