spring 在 JUnit 测试用例上获取 LazyInitializationException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19813492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting LazyInitializationException on JUnit Test Case
提问by Jamie White
Problem running JUnit Test inside a Spring MVC Application. Test 1 (insertTweet) seems to run fine, however on Test 2 I get an "LazyInitializationException" Exception (see full stactrace below). I understand why it is thrown but not sure why the session is closing and how to reopen it at the begining of every test 2 (or keep the existing session open for the remaining tests to complete)? I have pasted the entire StackTrace thrown along with Test Classes.
在 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.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.run(ParentRunner.java:193)
at org.junit.runners.ParentRunner.schedule(ParentRunner.java:52)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
at org.junit.runners.ParentRunner.access@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;
}
}
0(ParentRunner.java:42)
at org.junit.runners.ParentRunner.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)
com.project.user.User.tweets
采纳答案by roark
I've run into this and the error is a bit misleading. The Session
is not being closed.
我遇到了这个问题,这个错误有点误导。在Session
没有被关闭。
When you call userService.findByUserId(1);
it probably does a Join
to a Tweets
table and so you get this collection back:
当你调用userService.findByUserId(1);
它可能做了Join
一个Tweets
表,所以你得到这个集合回:
Hibernate.initialize(user.getTweets());
Hibernate does not initialize this collection by default. To initialize it, you can call Hibernate.initialize()
for example, like this:
Hibernate 默认不初始化这个集合。要初始化它,您可以Hibernate.initialize()
像这样调用:
@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;
}
Of course substitute getTweets()
for the actual method that returns the tweets
collection.
当然替换getTweets()
返回tweets
集合的实际方法。
回答by uvwxyz888
add the
@Transactional
on your test methods – ben75Nov 6 '13 at 14:29
添加
@Transactional
您的测试方法 – ben75 2013 年11 月 6 日 14:29
Yeah, I have solved the problem:
是的,我已经解决了这个问题:
@TestExecutionListeners({ServiceTestExecutionListener.class, TransactionalTestExecutionListener.class})
回答by ben75
You are missing the TransactionalTestExecutionListener
.
It is required and present by default when you don't define any TestExecutionListener yourself. But as soon as you define one explicitely : it is removed.
你错过了TransactionalTestExecutionListener
. 当您自己没有定义任何 TestExecutionListener 时,它是必需的并且默认存在。但是一旦您明确定义了一个:它就会被删除。
So declare it :
所以声明它:
@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional // The magic is here
public class YourClassTests {
...
}
See "Testing - Transaction management" of the 3.2.x Spring docs.
请参阅3.2.x Spring 文档的“测试 - 事务管理”。
回答by FabianoLothor
Enjoy
享受
##代码##