我首先没有提到这个问题的关键组成部分:我在这里使用TestNG.
我有一个执行持久性的DAO层.它作为我的小网络应用程序的一部分工作得很好(我有一个经典的控制器,服务,DAO层设计).如果需要,我可以使用我的XML更新此问题.
我的服务层
@Service
public class UserServiceImpl implements UserService {
@Autowired
private UserDao userDao;
@Override
public GoodVibeUserDetails getUser(String username) throws UsernameNotFoundException {
GoodVibeUserDetails user = userDao.getDetailsRolesAndImagesForUser(username);
return user;
}
// more methods...
}
我的DAO层
@Repository
public class UserDaoImplHibernate implements UserDao {
@Autowired
private SessionFactory sessionFactory;
// My methods using sessionFactory & "talking" to the Db via the sessionFactory
}
这是我的测试类
@Component
public class UserDaoImplHibernateTests{
@Autowired
private UserDao userDao;
private GoodVibeUserDetails user;
@BeforeMethod
public void beforeEachMethod() throws ParseException{
user = new GoodVibeUserDetails();
user.setUsername("adrien");
user.setActive(true);
// & so on...
}
/*
* When everything is fine - test cases
*/
@Test
public void shouldAcceptRegistrationAndReturnUserWithId() throws Exception{
assertNotNull(userDao) ;
user = userDao.registerUser(user);
assertNotNull(user.getId()) ;
}
// more test cases...
}
但是对于我的测试类Autowiring,userDao总是返回Null,我只是开始在Spring做测试而我有点迷失.任何指针都是受欢迎的.
鲍里斯特鲁霍夫回答后的最新编辑
import ...
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.junit.Assert.assertNotNull;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/applicationContext.xml")
public class UserDaoImplHibernateTests{
@Autowired
@Qualifier("userDao")
private UserDao userDao;
private GoodVibeUserDetails user;
@BeforeMethod
public void beforeEachMethod() throws ParseException{
user = new GoodVibeUserDetails();
user.setUsername("adrien");
user.setActive(true);
// & so on...
}
/*
* When everything is fine - test cases
*/
@Test
public void shouldAcceptRegistrationAndReturnUserWithId() throws Exception{
assertNotNull(userDao) ;
user = userDao.registerUser(user);
assertNotNull(user.getId()) ;
}
// more test methods...
}
这是我的applicationContext.xml
spring-beans-3.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd" >
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。