0

案例:我在@PostConstruct中加载用户对象,当尝试在任何测试方法中获取角色时,我得到延迟初始化异常,但是当在任何测试方法中加载用户对象然后获取角色时,一切正常

要求: 我希望能够使延迟初始化在测试方法中正常工作,而无需在每个测试方法中加载对象,也无需在 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);

   }



 }
4

2 回答 2

1

使用@Before代替@PostConstruct

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

@PostConstruct(它永远不会在事务中运行,即使显式标记为@Transactional)相反,@Before方法@After总是参与测试(仅回滚)事务。

于 2011-12-11T15:41:52.637 回答
0

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

于 2011-12-11T15:44:35.053 回答