1,拷贝jar包
junit-3.8.2.jar(4.x主要增加注解应用)
2,写业务类
package test.entity;
import test.service.UserService;
import java.util.List;
import java.util.Properties;
public class User {
private int id;
private String userName;
private UserService userService;
private List<String> userNameList;
private Properties props;
private String userCode;
public User(String userCode){
this.userCode = userCode;
}
public void setId(int id){
this.id = id;
}
public int getId(){
return id;
}
public void setUserName(String userName){
this.userName = userName;
}
public String getUserName(){
return userName;
}
public void setUserService(UserService userService){
this.userService = userService;
}
public UserService getUserService(){
return userService;
}
public void setUserNameList(List<String> userNameList){
this.userNameList = userNameList;
}
public List<String> getUserNameList(){
return userNameList;
}
public void setProps(Properties props){
this.props = props;
}
public Properties getProps(){
return props;
}
public String login(){
if("admin".equals(userName)) {
return "Success";
}else {
return "false";
}
}
}
3,定义测试类
测试类最好单独建立项目,或者单独定义文件夹存储,需要继承junit.framework.TestCase
4,增加测试方法
测试方法必须是public,不应该有返回值,方法名必须以test开头,无参数
测试方法是有执行先后顺序,按照方法的定义先后顺序
多个测试方法对同一个业务方法进行测试,一般每个逻辑分支结构都有测试到。
import junit.framework.TestCase;
import test.entity.User;
public class TestUser extends TestCase {
public void testUserLogin(){
User user = new User("1");
user.setUserName("admin");
String result = user.login();
assertEquals("Success",result);
}
}

5,测试类的生命周期方法
@Override
protected void setUp() throws Exception {
super.setUp();
System.out.println("start>>>>>>>");
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
System.out.println("end>>>>>>>");
}
setUp方法会在每一个测试方法前执行一次。tearDown方法会在每一个测试方法后执行一次
Junit单元测试&spm=1001.2101.3001.5002&articleId=142325342&d=1&t=3&u=7450830a428a470c805bdb01ff5afc7f)

被折叠的 条评论
为什么被折叠?



