Getting LazyInitializationException on JUnit Test Case

I've run into this and the error is a bit misleading. The Session is not being closed.

When you call userService.findByUserId(1); it probably does a Join to a Tweets table and so you get this collection back:

com.project.user.User.tweets

Hibernate does not initialize this collection by default. To initialize it, you can call Hibernate.initialize() for example, like this:

Hibernate.initialize(user.getTweets());

Of course substitute getTweets() for the actual method that returns the tweets collection.


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.

So declare it :

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

See "Testing - Transaction management" of the 3.2.x Spring docs.


Enjoy

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

...

}

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

Yeah, I have solved the problem:

        @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;
            }