Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send a mock object as JSON in mockmvc

Tags:

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?

like image 609
Sourabh Avatar asked Jun 13 '14 06:06

Sourabh


2 Answers

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());
}
like image 157
matsev Avatar answered Sep 19 '22 13:09

matsev


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

like image 45
Serge Ballesta Avatar answered Sep 17 '22 13:09

Serge Ballesta