我有一项我想测试的服务:
public class DepartmentServiceImpl implements DepartmentService {
@Autowired
private DepartmentDao departmentDao;
//... other functions
@Override
public Department getDepartment(int depid) {
return departmentDao.getDepartment(depid);
}
}
这是我的测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:sdnext-servlet.xml")
public class TestDepartmentDetails {
Department department = new Department();
DepartmentServiceImpl service = new DepartmentServiceImpl();
@Autowired
private DepartmentDao myDao;
@Test
public void testGetDepartment(){
assertEquals("lalalalalalala", service.getDepartment(98).getDepName());
}
为什么它会让我失败并抛出NullPointerException
?还有其他解决方案吗?
注意:这是一个使用Spring和Hibernate的应用程序。
答案 0 :(得分:1)
以这种方式试试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:sdnext-servlet.xml")
public class TestDepartmentDetails {
@Autowired
DepartmentService service;
@Test
public void testGetDepartment(){
assertEquals("lalalalalalala", service.getDepartment(98).getDepName());
}
答案 1 :(得分:0)
这里您手动创建实例,这在使用Spring时不是正确的方法。
请参阅下面的Spring文档:
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/
在这种情况下,您必须自动装配 DepartmentServiceImpl 服务,而不是 DepartmentDao 。