您的位置:首页 > 其它

关于在SSH2整合时,如何使用单元测试

2014-12-15 14:53 197 查看
在SSH2整合时,无论如何我们都要测试我们service层的方法是否正确可言,当测试通过的时候,就可以在Action中使用该方法了。现在我来讲一讲如何使用Junit4 来进行测试。

1,首先要下载一个junit4.jar

下载junit4.jar,然后将其复制到WEB-INF/lib中

下载地址:http://download.csdn.net/detail/zhangkai1992/8261857

2,比如我要测试的是UsersService类中的方法。

首先写UsersService类

public class UsersService  implements UsersServiceInter {

public Users checkUsers(Users users){
String hql="from Users where username=? and pwd= ?";
Object[] parameters = {users.getUsername(),users.getPwd()};
List<Users> list = null;
try {
list = this.executeQuery(hql, parameters);
} catch (Exception e) {
// TODO: handle exception
throw new RuntimeException("查询失败");
}
if(list.size()!=0){
return  list.get(0);
}else{
return null;
}
}
public boolean checkUsername(String username){
String hql="from Users where username=?";
Object[] parameters={username};
//Users users = (Users)this.uniqueQuery(hql, parameters);
List<Users> list = null;
try{
list=  this.executeQuery(hql, parameters);
}catch(Exception e){
System.out.println("搜索失败");
}
if(list.size()!=0){
return true;
}else{
return false;
}
}
public List<Users> getUsersByPage(int pageNow, int pageSize) {
// TODO Auto-generated method stub
String hql = "from Users order by id";
return this.executeQueryByPage(hql, null, pageNow, pageSize);
}

public int getPageCount(int pageSize) {
// TODO Auto-generated method stub
return this.queryPageCount("select count(*) from Users", null, pageSize);
}

public long getUsersAllRows() {
// TODO Auto-generated method stub
String hql = "select count(*) from Users";
return this.getAllRows(hql);
}

}

3,创建一个专门用于单元测试的开发包,比如com.zk.junit。在此包下创建usersServiceTest类

import org.junit.BeforeClass;

import org.junit.Test;

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.zk.domain.Users;

import com.zk.service.interfaces.UsersServiceInter;

public class UsersServiceTest {

private static UsersServiceInter usersService;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
try {
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
usersService = (UsersServiceInter)ac.getBean("usersService");
} catch (RuntimeException e) {
e.printStackTrace();
}
}
@Test
public void checkUsername() throws Exception{
System.out.println(usersService.checkUsername("admin"));
}
@Test
public void checkUsers() throws Exception{
Users users = new Users();
users.setUsername("admin");
users.setPwd("admin");
try{
users = usersService.checkUsers(users);
System.out.println(users.toString());
}catch(Exception e){
System.out.println("异常");
e.printStackTrace();
}
}

}

右击run,以junit单元测试运行,将看到结果如下图所示,表示单元测试试用成功。



其中@BeforeClass类似于初始化,在执行单元测试函数时,先加载。

@Test就是我们需要测试的函数,必须返回public void
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息