1. 程式人生 > >junit test中解決could not initialize proxy

junit test中解決could not initialize proxy

專案中把session的管理交給了spring,靠著openEntityManagerInViewFilter逍遙。今天寫junit測試的時候出現了許久未見的no session問題。最後找到了解決方案:
在junit測試類上加上@Transactional標籤,沒錯,就是service層新增的org.springframework.transaction.annotation標籤。然後就再也不報no session的問題了。

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Pageable; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import
org.springframework.transaction.annotation.Transactional; @RunWith(SpringJUnit4ClassRunner.class) @WebAppConfiguration @ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/applicationContext.xml", "file:src/main/webapp/WEB-INF/spring-mvc.xml", "file:src/main/webapp/WEB-INF/context-component.xml"
}) public class MessageServiceTest { @Autowired MessageService service; @Test @Transactional public void findAllTest() { Pageable pageable = new PageRequest(0, 10); Page<Message> messages = service.findAll(null, pageable); for( Message message : messages){ System.out.println(message.getTopic().getTopicTitle()); } } }