Mahmoud Saleh
Mahmoud Saleh

Reputation: 33605

lazy loading doesn't work with @Postconstruct

CASE: i load the user object in @PostConstruct, and when trying to get the roles in any test method, i get lazyinitialization exception, but when loading the user object in any test method and then getting the roles, everything works fine.

REQUIREMENT: i want to be able to make lazy initialization works fine in test methods without the need of loading the object in each test method, and also without the workaround of loading the collection in the init method, are there any good solution for such issue in unit test ?

   @RunWith(SpringJUnit4ClassRunner.class)
   @ContextConfiguration(locations = {
      "classpath:/META-INF/spring/applicationContext.xml",
      "classpath:/META-INF/spring/applicationSecurity.xml" })
   @TransactionConfiguration(defaultRollback = true)
   @Transactional
   public class DepartmentTest extends
      AbstractTransactionalJUnit4SpringContextTests {

   @Autowired
   private EmployeeService employeeService;

   private Employee testAdmin;

   private long testAdminId;

   @PostConstruct
   private void init() throws Exception {

    testAdminId = 1;
    testAdmin = employeeService.getEmployeeById(testAdminId);

   }


   @Test
   public void testLazyInitialization() throws Exception {

    testAdmin = employeeService.getEmployeeById(testAdminId);
    //if i commented the above assignment, i will get lazyinitialiaztion exception on the following line.
    Assert.assertTrue(testAdmin.getRoles().size() > 0);

   }



 }

Upvotes: 0

Views: 1652

Answers (2)

Tomasz Nurkiewicz
Tomasz Nurkiewicz

Reputation: 340743

Use @Before instead of @PostConstruct:

@org.junit.Before
public void init() throws Exception {
  testAdminId = 1;
  testAdmin = employeeService.getEmployeeById(testAdminId);
}

In contrary to @PostConstruct (which never runs within a transaction, even when explicitly marked with @Transactional), @Before and @After methods are always taking part in a test (rollback-only) transaction.

Upvotes: 1

Lucas
Lucas

Reputation: 14959

It wont help. JUnit framework constructs a new object for each test method anyway so even if you do get @PostConstruct to do what you want, it will not initialize once for all the methods. The only all method initialization is JUnits @BeforeClass which probably still isnt what you want because its static and gets run before the spring initialization. You could try other frameworks...

Upvotes: 0

Related Questions