0

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);

   }



 }

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

it worked fine, but the init method needed to be public, thanks for very quick reply.
0

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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.