案例:我在@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);
}
}