我有单元测试来测试休眠过程让我通过这个
下面是我的 AbstractDAO
public abstract class BaseDAO {
protected JdbcTemplate jdbcTemplate;
protected SessionFactory sessionFactory;
protected NamedParameterJdbcTemplate namedParameterJdbcTemplate;
...
@Autowired
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
this.namedParameterJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}
@Autowired
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
这是我的concreteDAO,它扩展了BaseDAO
public class LoginDAO extends BaseDAO implements InitializingBean {
private static final Logger log = Logger.getLogger(LoginDAO.class);
private MD5PasswordEncoder passwordEncoder;
private SaltSource saltSource;
public User getLoggedinUserByUserid(Long userid){
log.info("in getLoggedinUserByUserid");
User result = null;
Session session = sessionFactory.openSession();
try {
session.beginTransaction();
result = (User) session.get(User.class, userid);
session.getTransaction().rollback();
session.close();
} catch (Exception e) {
log.error(e,e);
session.getTransaction().rollback();
session.close();
}
return result;
}
...
}
这是我的junit
@Test
public void shouldReturnCorrectlyUserWhenCallingGetLoggedinUserByUseridMethod() {
// Given When
User adminUser = loginDAO.getLoggedinUserByUserid(1l);
// Then
assertNotNull(adminUser);
assertEquals("sadmin", adminUser.getUsername());
assertEquals("ecedee8662a0bcd15c157e5734056ac5", adminUser.getPassword());
assertEquals(1, adminUser.getStatus());
assertEquals("TS", adminUser.getFirstname());
assertEquals("Sys Admin Person", adminUser.getLastname());
assertEquals(0, adminUser.getIdType());
assertTrue(adminUser.getEnabled());
assertTrue(adminUser.getAuthenLocal());
assertTrue(StringUtils.isBlank(adminUser.getTitle()));
}
SessionFactory 在 BaseDAO 中注入正常,但是当它进入
Session session = sessionFactory.openSession();
时LoginDAO
,它变成了 null!
这怎么可能发生?需要一些解释,我该如何解决这个问题?