I am trying to test a controller method and I have an issue that probably has to do with lazy loading and I am therefore trying to set up a open entity manager in view filter for my tests.
Setup method:
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac)//
.addFilters(springSecurityFilterChain, new OpenEntityManagerInViewFilter())//
.defaultRequest(get("/").with(csrf())//
.secure(true))//
.build();//
...
Test method:
@Test
public void shouldNotAllowAdvertisementModification() throws Exception {
ChildminderAdvertisementInfo childminderAdvertisementInfo = new ChildminderAdvertisementInfo();
childminderAdvertisementInfo.setAddressReference(VALID_ADDRESS_REFERENCE);
ChildminderAdvertisement advertisement = helper.buildChildminderAdvertisement("balteo@yahoo.fr");
childminderAdvertisementInfo.setAdvertisement(advertisement);
CustomJacksonObjectMapper mapper = new CustomJacksonObjectMapper();
String jsonChildminderAdvertisementInfo = mapper.writeValueAsString(childminderAdvertisementInfo);
mockMvc.perform(post("/advertisement/childminder/edit/{advertisementId}", 1L).with(userDeatilsService("balteo@gmail.com"))//
.contentType(MediaType.APPLICATION_JSON)//
.header("X-Ajax", "true")//
.content(jsonChildminderAdvertisementInfo))//
.andDo(print())//
.andExpect(status().isForbidden());//
}
Object Mapper:
public class CustomJacksonObjectMapper extends ObjectMapper {
private static final long serialVersionUID = 1L;
public CustomJacksonObjectMapper() {
super();
configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);//FIXME
this.addMixInAnnotations(Curriculum.class, CurriculumMixin.class);
this.addMixInAnnotations(Advertisement.class, AdvertisementMixin.class);
this.addMixInAnnotations(Address.class, AddressMixin.class);
this.addMixInAnnotations(Message.class, MessageMixin.class);
this.addMixInAnnotations(Training.class, TrainingMixin.class);
this.addMixInAnnotations(WorkExperience.class, WorkExperienceMixin.class);
}
}
Exception stack trace:
com.fasterxml.jackson.databind.JsonMappingException: could not initialize proxy - no Session (through reference chain: com.bignibou.controller.advertisement.ChildminderAdvertisementInfo["advertisement"]->com.bignibou.domain.ChildminderAdvertisement["address"]->com.bignibou.domain.Address_$$_jvst68_a["reference"])
at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:232)
at
It seem the second filter is ignored by Spring Mvc Test and I still get the hibernate error... Can anyone please help?
I sorted the issue by:
Adding the following dependency to my project:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate4</artifactId>
<version>2.3.2</version>
</dependency>
Registering a Hibernate jackson module on my ObjectMapper as follows:
CustomJacksonObjectMapper mapper = new CustomJacksonObjectMapper();
mapper.registerModule(new Hibernate4Module());