junit test中解决could not initialize proxy - no Session

项目中把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 messages = service.findAll(null, pageable);
        for( Message message : messages){
            System.out.println(message.getTopic().getTopicTitle());
        }
    }

}

参考:
http://stackoverflow.com/questions/19813492/getting-lazyinitializationexception-on-junit-test-case

你可能感兴趣的:(spring)