java - How to use Gson TypeAdapter with an object mocked by Mockito? -
i mock object passed gson via typeadapter this:
@runwith(mockitojunitrunner.class) public class sceneexportertest { @test public void testwriter() { list<sceneobject> sceneobjects = mocksceneobjects(); gson gson = new gsonbuilder().registertypeadapter(sceneobject.class, new sceneexporter()).create(); string s = gson.tojson(sceneobjects); //this method ends exception. } private list<sceneobject> mocksceneobjects() { list<sceneobject> sceneobjects = new linkedlist<>(); (int = 0; < 50; i++) { sceneobjects.add(mocksceneobject(i)); } return sceneobjects; } private sceneobject mocksceneobject(int i) { sceneobject sceneobject = mock(sceneobject.class); //... return sceneobject; } }
my type adapter:
public class sceneexporter extends typeadapter<sceneobject> { @override public void write(jsonwriter out, sceneobject value) throws ioexception { out.name("position"); out.value(tovalue(value.getposition())); out.name("scale"); out.value(tovalue(value.getscale())); out.name("rotation"); out.value(tovalue(value.getrotation())); } @override public sceneobject read(jsonreader in) throws ioexception { return null; } }
but end such exception:
java.lang.unsupportedoperationexception: attempted serialize java.lang.class: com.editor.api.scene.objects.sceneobject. forgot register type adapter?
scene object pretty heavy object , don't want instantinate within test. there possibility mock it? not use spies.
the runtime type of instance of sceneobject
created in way: mock(sceneobject.class)
sceneobject$mockitomock$<someid>
.
the runtime type of instance of sceneobject
created in way: new sceneobject()
sceneobject
.
so, when gson's typeadapterruntimetypewrapper
looks registered typeadapter
in context mocked object not find 1 because sceneexporter
has been registered against sceneobject.class
.
what saying mocked sceneobject
not of type sceneobject
(it sub class of sceneobject
) hence gson not find bespoke type adapter.
if declare gson
...
gson gson = new gsonbuilder().registertypeadapter(mock(sceneobject.class).getclass(), new sceneexporter()).create();
... will find bespoke type adapter registration looks 'off' doesn't it? feels test-only specialisation.
if must mock sceneobject
think you'll need register inheritance aware type adapter if doing support test case feels test-only limitation bleeding 'main' source tree. so, perhaps simplest solutions are:
- create real instances of
sceneobject
- use mockito
spy
stub out specificsceneobject
getters invoked insceneexporter
Comments
Post a Comment