【问题标题】:Getting LazyInitializationException on JUnit Test Case在 JUnit 测试用例上获取 LazyInitializationException
【发布时间】:2013-11-17 18:33:37
【问题描述】:

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

}

【问题讨论】:

  • 您希望我们如何处理您展示的内容?发布您的配置和测试。

标签: spring hibernate junit jpa-2.0 spring-data


【解决方案1】:

享受

@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional // The magic is here
public class YourClassTests {

...

}

【讨论】:

    【解决方案2】:

    您缺少TransactionalTestExecutionListener。 当您自己没有定义任何 TestExecutionListener 时,它是必需的并且默认存在。但是一旦你明确定义了一个:它就会被删除。

    所以声明它:

    @TestExecutionListeners({ServiceTestExecutionListener.class, TransactionalTestExecutionListener.class})
    

    请参阅 3.2.x Spring 文档的“Testing - Transaction management”。

    【讨论】:

    • 我按照建议进行了更改,但仍然出现上述异常。
    • 在您的测试方法中添加@Transactional
    • 我也添加了。如果您正在扩展我正在做的 AbstractTransactionalJUnit4SpringContextTests 类,我认为所有这些都是不必要的。
    • 我在 JUnit 测试用例中解决了同样的问题,只需将 TransactionalTestExecutionListener 添加到侦听器即可。谢谢。 :)
    【解决方案3】:

    在您的测试方法中添加 @Transactionalben75 2013 年 11 月 6 日 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;
                }
    

    【讨论】:

    【解决方案4】:

    我遇到了这个问题,这个错误有点误导。 Session 没有被关闭。

    当您调用userService.findByUserId(1); 时,它可能会对Tweets 表执行Join,因此您可以取回这个集合:

    com.project.user.User.tweets
    

    Hibernate 默认不初始化这个集合。要初始化它,你可以调用Hibernate.initialize(),例如:

    Hibernate.initialize(user.getTweets());
    

    当然用getTweets() 代替返回tweets 集合的实际方法。

    【讨论】:

    • 这似乎行得通。但是,我正在使用 JPA 2,并且在 JPA 实体类中包含“Hibernate.initialize()”似乎很奇怪。难道是junit调用hibernate而不是jpa?
    • 是的,这很奇怪 :-) 然后需要急切地获取实体中的 Tweets 集合(它将是惰性的,即默认情况下已检索但未初始化)。尝试使用@OneToMany(fetch=FetchType.EAGER)注释
    • 我不确定你的意思?除非我遗漏了什么,否则如果我明确地将其定义为“急切地”加载集合,我希望它能够做到这一点。此外,我想先用尽所有其他选项。
    • 在这种情况下急切加载集合有什么问题?
    • 推文集合可能包含很多记录。如果我要“急切地”加载此集合,那么每次加载“用户”对象时,它也会加载推文集合,这可能会导致性能问题。
    猜你喜欢
    • 2012-01-26
    • 2013-04-08
    • 2013-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-26
    相关资源
    最近更新 更多