spring - 在 JUnit 测试用例上获取 LazyInitializationException

标签 spring hibernate junit jpa-2.0 spring-data

在 Spring MVC 应用程序中运行 JUnit 测试时出现问题。测试 1 (insertTweet) 似乎运行良好,但是在测试 2 中我得到一个“LazyInitializationException”异常(参见下面的完整 stactrace)。我理解为什么会抛出它,但不确定 session 为何关闭以及如何在每个测试 2 开始时重新打开它(或保持现有 session 打开以完成剩余测试)?我已经粘贴了与测试类一起抛出的整个 StackTrace。

org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.project.user.User.tweets, could not initialize proxy - no Session
    at org.hibernate.collection.internal.AbstractPersistentCollection.throwLazyInitializationException(AbstractPersistentCollection.java:566)
    at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:186)
    at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:545)
    at org.hibernate.collection.internal.AbstractPersistentCollection.write(AbstractPersistentCollection.java:370)
    at org.hibernate.collection.internal.PersistentBag.add(PersistentBag.java:291)
    at com.project.core.tweet.Tweet.<init>(Tweet.java:113)
    at com.project.core.service.impl.FanoutServiceTester.insertTweet(FanoutServiceTester.java:69)
    at com.project.core.service.impl.FanoutServiceTester.testInsertRetweet(FanoutServiceTester.java:62)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({ServiceTestExecutionListener.class})
@ActiveProfiles("test")
public abstract class AbstractServiceImplTest extends AbstractTransactionalJUnit4SpringContextTests {

    @PersistenceContext
    protected EntityManager em;

    @Autowired protected TweetService tweetService;
    @Autowired protected UserService userService;

}


public class FanoutServiceTester extends AbstractServiceImplTest{
    private static User user = null;
    private static User userTwo = null;



    @Before
    public void setUp() throws Exception {

        user = userService.findByUserId(1);


        //UserTwo Follows User One
        userTwo  = userService.findByUserId(2);



    }


    @Test
    public final void testInsertTweet() {       
        insertTweet();

        //Assert Here

    }



    @Test
    public final void testInsertRetweet() {
        insertTweet();
        //Assert Here

    }


    private Tweet insertTweet(){
        Tweet tweet = new Tweet(user);
        String text = "This is a Message";  
        tweet.setTweetText(text);
        Tweet saved = tweetService.save(tweet);
        return saved;
    }

}

最佳答案

add the @Transactional on your test methods – ben75 Nov 6 '13 at 14:29

是的,我已经解决了这个问题:

        @RunWith(SpringJUnit4ClassRunner.class)
        @ContextConfiguration(locations = { "classpath*:applicationContext.xml"})
        @Transactional
        public class UserinfoActionTest extends StrutsSpringJUnit4TestCase<UserinfoAction> {
                @Test
            public void testLogin2(){
                          request.setParameter("jsonQueryParam", param);
                String str = null;
        try {

                    str = executeAction("/login.action");
                    HashMap<String,List<TUserinfo>> map = (HashMap<String,List<TUserinfo>>)findValueAfterExecute("outDataMap"); }
 catch (Exception e) {
                    e.printStackTrace();
                }

            }


        @Controller
        @Results({  
            @Result(name="json",type="json"
                    , params={"root","outDataMap","excludeNullProperties","true"
                            ,"excludeProperties","^ret\\[\\d+\\]\\.city\\.province,^ret\\[\\d+\\]\\.enterprise\\.userinfos","enableGZIP","true"
                    })
        })
        public class UserinfoAction extends BaseAction {
                    @Action(value="login")

            public String login(){
                if(jsonQueryParam!=null && jsonQueryParam.length()>0)
                {
                    user = JsonMapper.fromJson(jsonQueryParam, TUserinfo.class);
                }
                Assert.notNull(user);
                 //RESULT="ret" addOutJsonData: put List<TUserinfo> into outDataMap with key RESULT for struts2 JSONResult  
                addOutJsonData(RESULT, service.login(user));
                return JSON;
            }

关于spring - 在 JUnit 测试用例上获取 LazyInitializationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19813492/

相关文章:

java.lang.NoClassDefFoundError : org/springframework/transaction/interceptor/TransactionInterceptor 错误

java - 如何接收 convertAndSend 发送的内容?

java - @parameters方法在@beforeclass方法之前执行

java - 在项目中使用 mockito-inline 会抛出 "Mockito cannot mock this class"错误

mysql - 在我的 SQL 数据库上执行查询时连接被拒绝

java - : tag in the Spring template app? bean 是什么

hibernate - 如何更改已弃用的 HibernateEntityManagerFactory(5.2.10) 以添加监听器?

java - 使用 hibernate 和 mysql 检索多态实体

hibernate - 为 hibernate 3.6 配置 pom.xml

java - 使用 jsonPath 匹配 boolean 真值