开发者

is it possible to mock transient fields in tests?

I have a class that contains a transient field. But the other part of the class is serializable. In the tests I mock the field and the class and use the mocked class object in a deep copy function which looks like below:

try {
      final ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
      objectOut = new ObjectOutputStream(bytesOut);
      // serialize and pass the object
      objectOut.writeObject(original);
      objectOut.flush();
      final ByteArrayInputStream bytesIn =
          new ByteArrayInputStream(bytesOut.toByteArray());
      objectIn = new ObjectInputStream(bytesIn);
      @SuppressWarnings("unchecked")
      final T clone = (T) objectIn.readObject();
      // return the new object
      return clone;
    }
catch () {...}

the writeObject(original) method is supposed to write all non-transient and non-static fields. But I've got an error saying java.io.NotSerializableException for the mock transient field. I wonder if th开发者_JAVA技巧e transient field cannot be recognised in the tests? I use mockito as my framework.


What do you mean by "I mock the field and the class" ?

I just whipped up a quick test based on this dummy class:

public class DummyClass implements Serializable {
    private static final long serialVersionUID = -4991860764538033995L;

    transient private ChildClass child;

    ...
}

ChildClass is just an empty (non-Serializable) class. The test looks like this:

...
DummyClass dc = new DummyClass();
ChildClass mockChild  = mock(ChildClass.class);
dc.setChild(mockChild);
copier.copy(dc);

... and that doesn't throw any NotSerializableException.

What are you trying to test? The deep-copier or the class that is passed to it?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜