I want to send a mock object in the controller via MockMvc with content type JSON. But when I am trying to serialize the mock the error is:
java.lang.UnsupportedOperationException: Expecting parameterized type, got interface org.mockito.internal.MockitoInvocationHandler.
Are you missing the use of TypeToken idiom?
My code is as following:
@Test
public void testSomething(){
String xyz = "";
Integer i = 10;
SomeClass inst = mock(SomeClass.class, withSettings().serializable());
when(inst.getProperty1()).then(xyz);
when(inst.getProperty2()).then(i);
Gson gson = new Gson();
String json = gson.toJson(inst); // this is creating error
this.mockmvc.perform(put("/someUrl/").contentType(MediaType.JSON).content(json)).andExpect(status().isOk());
}
Can someone tell me what I'm missing?
I propose that you create a stub of your SomeClass
that returns known values for the getProperty1()
and getProperty2()
method. Depending on how SomeClass
is implemented, you could either create a new
instance of it directly, subclass and override some methods, create an anonymous inner class if it is an interface, etc.
@Test
public void testSomething(){
String xyz = "";
Integer i = 10;
// alt 1:
SomeClass stub = new SomeClass(xyz, i);
// alt 2:
SomeClass stub = new StubSomeClass(xyz, i); // StubSomeClass extends SomeClass
// alt 3:
SomeClass stub = new SomeClass() {
@Override
String getProperty1() {
return xyz;
}
@Override
Integer getProperty2() {
return i;
}
}
Gson gson = new Gson();
String json = gson.toJson(stub);
this.mockmvc.perform(put("/someUrl/")
.contentType(MediaType.APPLICATION_JSON).content(json))
.andExpect(status().isOk());
}
Even if it was possible, submitting a mock object to a JSON converter would suppose a unit test dedicated to that operation : the mock object may have many attributes and methods far beyond the real class and the serialization could lead to a really strange result.
IMHO, as it is a unit test, you should write by hand the json serialized String. And you can do other tests if you need to control how Gson does the serialization
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With