Java 单元测试(Junit Test)
说到单元测试,不得不说Junit框架,它提供了居于方法的就能直接运行某方法;
引入Junit包
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;
public class JunitTest {
@BeforeClass
public static void testBeforeClass()
{
System.out.println("======> testBeforeClass");
}
@Before
public void testBefore()
{
System.out.println("======> testBefore");
}
@Test
public void testHelloword()
{
System.out.println("======> test");
}
@After
public void testAfter()
{
System.out.println("======> testAfter");
}
@AfterClass
public static void testAfterClass()
{
System.out.println("======> testAfterClass");
}
@Ignore
public void testIgnore()
{
System.out.println("======> testIgnore");
}
}
代码写好了,那怎样运行呢?
过程如下:
- 鼠标右键选中方法testHelloword()
- Run As -> 1 Junit Test (正常运行)
- Debug As -> 1 Junit Test (debug运行)
运行结果如下
======> testBeforeClass
======> testBefore
======> test
======> testAfter
======> testAfterClass
因此我可以总结出:
- 一个单元测试用例执行顺序为: @BeforeClass –> @Before –> @Test –> @After –> @AfterClass
- 每一个测试方法的调用顺序为: @Before –> @Test –> @After