JUnit的基本使用
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void info()
{
System.out.println("the stu info:"+this.age+" "+this.id+" "+this.name);
}
}
package com.test.unittest;
public class Teacher {
String tname;
String tage;
public Teacher(String tname, String tage) {
super();
this.tname = tname;
this.tage = tage;
}
public String getTname() {
return tname;
}
public void setTname(String tname) {
this.tname = tname;
}
public String getTage() {
return tage;
}
public void setTage(String tage) {
this.tage = tage;
}
public void info(){
System.out.println("the teacher info:"+this.tage+" " +this.tname);
}
}
后面这部分是对两个类进行的单元测试以及一个组合方式的使用
package com.Unittest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.test.unittest.Student;
public class StudentTest {
Student stu=new Student(1,23,"令狐冲");
@Before
public void setUp(){
System.out.println("Student Initial");
}
@Test
public void infoTest()
{
stu.info();
}
@After
public void tearDown(){
System.out.println("Student Destroy");
}
}
package com.Unittest;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import com.test.unittest.Teacher;
public class TeacherTest {
Teacher teacher=new Teacher("风清扬","90");
@Before
public void setUp(){
System.out.println("Teacher Initial");
}
@Test
public void infoTest()
{
teacher.info();
}
@After
public void tearDown(){
System.out.println("Teacher Destroy");
}
}
package com.Unittest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import com.test.unittest.Student;
@RunWith(Suite.class)
@SuiteClasses({StudentTest.class,TeacherTest.class})
public class AllTest {
}
/*输出的结果如下:
Student Initial
the stu info:23 1 令狐冲
Student Destroy
Teacher Initial
the teacher info:90 风清扬
Teacher Destroy
*/
补充说明:
写作业的时候把测试类一个一个手敲进去,真是太out了,还是用eclipse中自带的生成JUnit test的类比较好一点,直接在测试的那个package下面,创建一个新的JUnit Test Class 选定版本以及选定class under test 这个表示你希望生成哪一个类的测试类,这样生成的测试类中命名也比较规范,比如相同的方法名不同参数的方法,连参数类型都写上去了,比以前直接用a b c d...1 2 3 4....来区别同名的方法正规多了....