笔记本 myeclipse
1,首先要下载一个junit4.jar下载junit4.jar,然后将其复制到WEB-INF/lib中
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
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();}}}
右击run,以junit单元测试运行其中@BeforeClass类似于初始化,在执行单元测试函数时,先加载。@Test就是我们需要测试的函数,必须返回public void