当我使用MockMvc、Mockito和Jackson测试Spring控制器时,遇到了这个问题,因此我创建了一个简单的类来测试Jackson的行为。我使用的是jackson-databind:2.3.1和mockito-core:1.9.5。
给定这个类:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.Serializable;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class Person implements Serializable {
private String name;
private int age;
// Public getters and setters...
public static void main(String[] args) {
String name = "Bob";
int age = 21;
ObjectMapper objectMapper = new ObjectMapper();
// attempt serialization with real object
Person person = new Person();
person.setName(name);
person.setAge(age);
try {
System.out.println(objectMapper.writeValueAsString(person));
} catch (JsonProcessingException e) {
e.printStackTrace();
System.err.println("Failed to serialize real object");
}
// attempt serialization with mock object
Person mockPerson = mock(Person.class);
when(mockPerson.getName()).thenReturn(name);
when(mockPerson.getAge()).thenReturn(age);
try {
System.out.println(objectMapper.writeValueAsString(mockPerson));
} catch (JsonProcessingException e) {
e.printStackTrace();
System.err.println("Failed to serialize mock object.");
}
}
Jackson可以将真实对象进行序列化,但是当它尝试序列化模拟对象时,会抛出JsonMappingException异常。通过代码调试,发现它重复地调用serializeFields(bean, jgen, provider),并卡在内部的Mockito属性上。
所以,我的问题是:有没有办法强制Jackson使用getter方法?我尝试在类上使用@JsonIgnoreProperties,在字段上使用@JsonIgnore,在方法上使用@JsonProperty(不同组合尝试过),但都没有成功。或者,我必须编写自己的自定义序列化程序吗?
谢谢!