延迟加载不适用于@Postconstruct

时间:2011-12-11 15:37:56

标签: hibernate spring unit-testing lazy-loading lazy-initialization

CASE:我在 @PostConstruct 中加载用户对象,并尝试在任何测试方法中获取角色 < / strong>,我得 lazyinitialization例外,但加载 用户对象测试方法然后获取角色,一切正常

要求:我希望能够使懒惰初始化在测试方法中正常工作,而无需在每个测试方法中加载对象,也无需在init中加载集合的解决方法方法,在单元测试中有没有解决这个问题的好方法?

   @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 个答案:

答案 0 :(得分:1)

使用@Before代替@PostConstruct

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

@PostConstruct相反(即使在明确标有@Transactional时,也永远不会在事务中运行),@Before@After方法始终参与测试(仅回滚)事务。

答案 1 :(得分:0)

它不会有帮助。无论如何,JUnit框架为每个测试方法构造一个新对象,所以即使你得到@PostConstruct来做你想做的事情,它也不会为所有方法初始化一次。唯一的所有方法初始化是JUnits @BeforeClass,它可能仍然不是你想要的,因为它的静态并在spring初始化之前运行。你可以尝试其他框架......