JUnit
注释是给人看的,注解是给程序和编译器看的。
写好一个没有main函数的实体Person类,并且不想在main函数中来测试这个类中的方法:
我们一般使用JUnit测试:
- 建一个Junit.test包
- 在这个包下建一个Junit test case,命名为PersonTest.java
- 在Junit的测试用例PersonTest.java类中,建 testRun()、testEat() 等等测试方法,并加注解@Test,需要导入jar包和import导包(myeclipse会自动完成)。
- 最后,Run as - JUnit Test。
其实,在导入JUnit的jar包后,直接在实体Person类中的方法上加@Test注解,也能直接测试这些方法了。
但是,
建JUnit测试用例时候有四个附加选项:setUP()、tearDown()、setUpBeforeClass()、tearDownAfterClass() :
- setUP() 方法会自动加上 @Before 注解,此方法在每个测试方法运行之前运行,作用:可以初始化一些东西。
- tearDown() 方法会自动加上 @After 注解,此方法在每个测试方法运行之后运行,作用:可以销毁一些东西,释放资源。
package Junit.test;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import cn.mengmei.Person;
public class PersonTest2 {
Person p = null;
@Before
public void setUp() throws Exception {
p = new Person();
System.out.println("初始化一些东西:"+p);
}
@After
public void tearDown() throws Exception {
p = null;
System.out.println("销毁一些东西,释放一些资源!");
}
@Test
public void testEat() {
p.eat();
}
@Test
public void testRun() {
p.run();
}
@Test
public void testSleep() {
p.sleep();
}
}
运行结果:
初始化一些东西:cn.mengmei.Person@23365dcc
............eat...........
销毁一些东西,释放一些资源!
初始化一些东西:cn.mengmei.Person@3cb243d7
............run...........
销毁一些东西,释放一些资源!
初始化一些东西:cn.mengmei.Person@5b83f762
............sleep...........
销毁一些东西,释放一些资源!
- setUpBeforeClass() 方法会自动加上 @BeforeClass 注解,此方法在类加载的时候运行,作用:在类加载的时候初始化一些东西。
- 、tearDownAfterClass() 方法会自动加上 @AfterClass 注解,此方法在类销毁的时候运行,作用:在类销毁的时候释放一些资源。
package Junit.test;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import cn.mengmei.Person;
public class PersonTest3 {
Person p = new Person();
@BeforeClass
public static void setUpBeforeClass() throws Exception {
System.out.println("在类加载的时候运行!");
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
System.out.println("在类销毁的时候运行!");
}
@Test
public void testEat() {
p.eat();
}
@Test
public void testRun() {
p.run();
}
@Test
public void testSleep() {
p.sleep();
}
}
运行结果:
在类加载的时候运行!
............eat...........
............run...........
............sleep...........
在类销毁的时候运行!