从JUnit示例开始:
package com.example.myapplication;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() {
assertEquals(4, 2 + 2);
}
}
- 注解:JUnit4中,支持用注解的方式标注测试方法。
- @Test:说明该方法是测试方法,测试方法必须是public void,可以抛出异常
- @Ignore:忽略该测试方法。在JUnit4中,在不想运行某个测试方法使,可以加上注解。
- @Before:它会在每个测试方法执行前都调用一次
- @After:与@Before对应,它会在每个测试方法执行完后都调用一次
执行顺序before ->test1->after->before->test2->after - @BeforeClass&&AfterClass
与@Before不同的是,@BeforeClass注解的方法只会为一个测试类执行一次,@AfterClass同理。
注意:该注解的测试方法必须是public static void修饰的。
示例:
package com.example.myapplication; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class TestJUnitLifeCycle { @BeforeClass public static void init(){ System.out.println("----init-----"); } @Before public void setUp(){ System.out.println("----setup----"); } @After public void teardown(){ System.out.println("-----teardown-----"); } @AfterClass public static void finish(){ System.out.println("-----finish----"); }/* @Test public void addition_isCorrect() { assertEquals(4, 2 + 2); }*/ @Test public void test1() { System.out.println("test1"); } @Test public void test2() { System.out.println("test2"); } }
运行结果:
----init-----
----setup----
test1
-----teardown-----
----setup----
test2
-----teardown-----
-----finish----