我正在尝试测试控制器方法,我有一个可能与延迟加载有关的问题,因此我尝试在视图过滤器中为我的测试设置一个开放的实体管理器。
设置方法:
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(wac)//
.addFilters(springSecurityFilterChain, new OpenEntityManagerInViewFilter())//
.defaultRequest(get("/").with(csrf())//
.secure(true))//
.build();//
...
测试方法:
@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());//
}
对象映射器:
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);
}
}
异常堆栈跟踪:
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
Spring Mvc Test似乎忽略了第二个过滤器,我仍然遇到了休眠错误......有人可以帮忙吗?
答案 0 :(得分:3)
我按问题排序了问题:
将以下依赖项添加到我的项目中:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-hibernate4</artifactId>
<version>2.3.2</version>
</dependency>
在我的ObjectMapper上注册Hibernate jackson模块,如下所示:
CustomJacksonObjectMapper mapper = new CustomJacksonObjectMapper();
mapper.registerModule(new Hibernate4Module());