按照Spring的推荐(原话:You should not normally use the Spring container for unit tests: simply populate your POJOs in plain JUnit tests!),在单元测试时,你不应该依赖于Spring容器。换言之,你不应该在单元测试时启动ApplicatonContext并从中获取Bean,相反你应该通过模拟对象完成单元测试。而集成测试的前提则是事先装配好模块和模块之间的关联类,如将DAO层真实的UserDao和LoginLogDao装配到UserServiceImpl再进行测试。具体装配工作是在Spring配置文件中完成的,因此在一般情况下,集成测试需要启动Spring容器,你可以在测试类中简单地从Spring容器中取出目标Bean进行测试。
需要测试的业务接口
假设我们的应用中拥有一个UserService业务层接口,它拥有4个业务方法,其代码如下所示:
代码清单1 UserServie接口
package com.baobaotao.service;
import com.baobaotao.domain.User;
import org.springframework.transaction.annotation.Transactional;
@Transactional
public interface UserService {
boolean hasMatchUser(String userName,String password);
User findUserByUserName(String userName);
void loginSuccess(User user);
void registerUser(User user);
}
我们通过UserServiceImpl对UserService提供了实现:
代码清单2 UserServiceImpl实现UserService接口
package com.baobaotao.service;
import com.baobaotao.dao.LoginLogDao;
import com.baobaotao.dao.UserDao;
import com.baobaotao.domain.LoginLog;
import com.baobaotao.domain.User;
public class UserServiceImpl implements UserService {
private UserDao userDao;
private LoginLogDao loginLogDao;
public boolean hasMatchUser(String userName, String password) {
int matchCount =userDao.getMatchCount(userName, password);
return matchCount > 0;
}
public User findUserByUserName(String userName) {
return userDao.findUserByUserName(userName);
}
public void loginSuccess(User user) {
user.setCredits( 5 + user.getCredits());
LoginLog loginLog = new LoginLog();
loginLog.setUserId(user.getUserId());
loginLog.setIp(user.getLastIp());
loginLog.setLoginDate(user.getLastVisit());
userDao.updateLoginInfo(user);
loginLogDao.insertLoginLog(loginLog);
}
public void setLoginLogDao(LoginLogDao loginLogDao) {
this.loginLogDao = loginLogDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
}
UserServiceImpl引用了两个DAO层的类(UserDao和LoginLogDao)共同实现UserService的接口,在UserServiceImpl开放使用之前,我们有必须对其进行集成测试,以保证实现逻辑的正确性。
文章来源于领测软件测试网 https://www.ltesting.net/