In a Spring Boot 1.5.9 project, I'm currently trying to use @WebMvcTest
to run a test against one of my controllers. The entity being operated on has a @JsonDeserializer()
annotation on one of its properties pointing to a custom class. I'm attempting to mock the result of the deserialize()
call in a test without invoking the body.
However, when trying to do the following, I'm getting a NullPointerException error on a line within the deserialize()
method, which suggests the actual method body is being executed:
@Autowired
private MockMvc mvc;
@MockBean
private MyDeserializer myDeserializer
[...]
@Test
public void myTestMethod() {
doReturn(myDeserializedValue)
.when(myDeserializer)
.deserialize(
any(JsonParser.class),
any(DeserializationContext.class)
);
this.mvc.perform([...]) // perform mvc call that would invoke myDeserializer
logger.debug("Call complete"); // never gets to this line
}
I'm assuming the custom deserializer class is being invoked (possibly new
ed up) outside of the knowledge of Spring's ApplicationContext.
Is there any way to mock a custom deserializer, or do I need to bump this class up to use the full ApplicationContext via @SpringBootTest
and let it fully execute?
If you want Jackson to use a specific deserializer object instance you need to register it via a module on the ObjectMapper instance. See the docs for an example with a serializer; you'll have to modify it slightly for your deserializer.
Otherwise, I assume Jackson will just instantiate a new instance of your class every time and never use your mock (or bean?) at all.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.