多语言展示
当前在线:615今日阅读:126今日分享:42

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

在SSH2整合时,无论如何我们都要测试我们service层的方法是否正确可言,当测试通过的时候,就可以在Action中使用该方法了。现在我来讲一讲如何使用Junit4 来进行测试。
工具/原料

笔记本 myeclipse

方法/步骤
1

1,首先要下载一个junit4.jar下载junit4.jar,然后将其复制到WEB-INF/lib中

2

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 list = null;try {list = this.executeQuery(hql, parameters);} catch (Exception e) {// TODO: handle exceptionthrow 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 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 getUsersByPage(int pageNow, int pageSize) {// TODO Auto-generated method stubString hql = 'from Users order by id';return this.executeQueryByPage(hql, null, pageNow, pageSize);}public int getPageCount(int pageSize) {// TODO Auto-generated method stubreturn this.queryPageCount('select count(*) from Users', null, pageSize);}public long getUsersAllRows() {// TODO Auto-generated method stubString hql = 'select count(*) from Users';return this.getAllRows(hql);}}

3

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;@BeforeClasspublic static void setUpBeforeClass() throws Exception {try {ApplicationContext ac = new ClassPathXmlApplicationContext('applicationContext.xml');usersService = (UsersServiceInter)ac.getBean('usersService');} catch (RuntimeException e) {e.printStackTrace();}}@Testpublic void checkUsername() throws Exception{System.out.println(usersService.checkUsername('admin'));}@Testpublic 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();}}}

4

右击run,以junit单元测试运行其中@BeforeClass类似于初始化,在执行单元测试函数时,先加载。@Test就是我们需要测试的函数,必须返回public void

推荐信息