0

I'm doing JUnit for a SSH project. First, I met the org.hibernate.LazyInitializationException when I doing a @Test method. and I had done some research and resolved it. What I did is add Setup and TearDown which used to bind session resource.

These 2 methods are like this:

@Before
public void setup(){
    System.out.println("Setup() running....");
    String filename = "WebContent\\WEB-INF\\classes\\applicationContext.xml";
    ctx = new FileSystemXmlApplicationContext(filename);
    sf = (SessionFactory) ctx.getBean("sessionFactory");
    Session s = sf.openSession();
    TransactionSynchronizationManager.bindResource(sf, new SessionHolder(s));
}

@After
public void tearDown(){
    System.out.println("TearDown() running....");
    SessionHolder holder = (SessionHolder)TransactionSynchronizationManager.getResource(sf);
    Session s = holder.getSession();
    s.flush();
    TransactionSynchronizationManager.unbindResource(sf);
    SessionFactoryUtils.closeSession(s);
}

private SessionFactory sf;
private ApplicationContext ctx;

And then I write another method, but this exception raised again! It's weird. I re-run the first test method, it works. But the second one did not.

The first test method like this:

@Test
public void testFindAll() {
    UserGroupService userggroupService = (UserGroupService) ctx.getBean("UserGroupService");

    try {
        List groups = userggroupService.findAll();
        System.out.println(groups);
        if (groups != null){
            for (Object grp : groups){
                UserGroupBean group = (UserGroupBean) grp;
                System.out.printf("id=%d, name=%s, %d members\n", group.getId(), group.getName(), group.getMembers()==null?0:group.getMembers().size());
                if (group.getMembers() != null){
                    for(UserBean user: group.getMembers()){
                        System.out.printf("\tuser-%d, %s\n", user.getUserID(), user.getName());
                    }
                }
            }
        }
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

The second test method like this:

@Test
public void testDeleteRel() {
    String filename = "WebContent\\WEB-INF\\classes\\applicationContext.xml";
    ApplicationContext ctx = new FileSystemXmlApplicationContext(filename);

    UserGroupService service = (UserGroupService) ctx.getBean("UserGroupService");


    try {
        UserGroupBean userGroup = new UserGroupBean();
        userGroup.setId(1L);
        UserGroupBean group = (UserGroupBean) service.getUserGroup(userGroup);
        List<UserBean> members = group.getMembers();
        System.out.println(members.size()+" members");
    //  members.remove(0);
    //  service.updateUserGroup(group);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

The PO code like this:

@Entity
@Table(name = "UserGroupBean")
public class UserGroupBean implements UserGroup {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    @ManyToMany(targetEntity = UserGroupBean.class, 
        cascade = CascadeType.REFRESH, fetch = FetchType.LAZY)
    @JoinTable(name = "UserGroupParents", joinColumns = { @JoinColumn(name = "group_id") }, inverseJoinColumns = { @JoinColumn(name = "parent_id") })
    //@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    private List<UserGroupBean> parents;

    @ManyToMany(targetEntity = UserBean.class, 
        cascade = CascadeType.REFRESH, fetch = FetchType.LAZY)
    @JoinTable(name = "UserGroupMembers", joinColumns = { @JoinColumn(name = "group_id") }, inverseJoinColumns = { @JoinColumn(name = "user_id") })
    //@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
    private List<UserBean> members;

    // Getters and setters ...

My question is: Why the same @Before and @After code, but only 1 method can run well? What I missed?

Thanks

2 Answers2

0

well if i had understood what you are asking , in your second Test method , you try to initialize the application Context once more , although it has been initialized in the before() method. This is not a valid way to start spring context in junit. Refer to those examples which might resolve yout is : Spring Junit or Spring Junit 2

AntJavaDev
  • 1,089
  • 1
  • 15
  • 22
0

For error org.hibernate.LazyInitializationException use

@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@Transactional
public class TestAnything{
   ...
}