0

工作CASE:我加载用户对象@PostConstruct,并试图让角色任何测试方法的时候,我得到惰性初始模式例外,但是当装载任何测试方法,然后让角色的用户对象,一切工作正常懒加载不@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); 

    } 



} 

回答

1

使用@Before而不是@PostConstruct

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

在违背@PostConstruct(从未在一个事务中运行,即使明确标有@Transactional),@Before@After方法总是参加一个测试(仅回滚)事务。

+0

它工作正常,但init方法需要公开,感谢您的快速回复。 –

+0

更正,C&P错误,谢谢。 –

0

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