Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing a mock throws exception

I am trying to test my controller using mockMvc and mockito. The actual controller body is as following :

Message createXYZ(@RequestBody XYZ inst){
   //creates XYZ
}

Now for pushing the values via request body, I am creating a JSON using GsonBuilder by serializing XYZ. Here is the structure for class XYZ :

class XYZ{

  List<Y> listofYs;
  //some other properties as well
}

I am creating and setting a mock for List listofYs and when Gson is trying to serialize an instance of XYZ that has a mocked listofYs its generating NPE.

Is there a way around or is it that I am doing it completely wrong?

like image 240
Sourabh Avatar asked Jun 12 '14 12:06

Sourabh


2 Answers

According to the Mockito documentation, you can make a mock serializable:

List serializableMock = mock(List.class, withSettings().serializable());
like image 69
Stefan Walter Avatar answered Oct 19 '22 18:10

Stefan Walter


Similarly to Stefan's answer above, mocks created via annotations can be marked as serializable through:

@Mock(serializable = true)
List serializableMock;
like image 8
Ben Watson Avatar answered Oct 19 '22 19:10

Ben Watson