- //一个简单的例子
- public class Example {
- @Test
- public void method() {
- org.junit.Assert.assertTrue( new ArrayList().isEmpty() );
- }
- }
@before
@after
@before class
@after class
以上注释实现方式类似。
org.junit
Annotation Type Before 注释类型 Before
@Retention(value=RUNTIME) @Target(value=METHOD) public @interface Before
When writing tests, it is common to find that several tests need similar objects created before they can run. Annotating a public void
method with @Before
causes that method to be run before the Test
method. The @Before
methods of superclasses will be run before those of the current class.
当编写测试的时候,会发现有时候很多方法需要相同的前置条件,在一个PUBLIC VOID 的方法前面加@Before,会使所有的测试方法运行之前,先运行@Before注释的方法。
Here is a simple example:
以下是一个简单的示例
public class Example { List empty; @Before public void initialize() { empty= new ArrayList(); } @Test public void size() { ... } @Test public void remove() { ... } } @after跟@Before相对,在每次测试方法以后运行。
@before class是在一个测试类之前,意思也就是一个测试类前只运行一次
@after class与上面的方法相对。
Assert
断言,assertTrue方法,可以通过静态方法引入方式引入。
import static org.junit.Assert.assertEquals;
@Test可以有两个参数,第一个参数expected.后面跟期望抛出的对象类型.
@Test(expected=IndexOutOfBoundsException.class)
public void outOfBounds() {
new ArrayList<Object>().get(1);
}
简单的性能测试,如 @Test(timeout=100)
@Test(timeout=100) public void infinity() {
while(true);
}
感觉JUNIT4这个工具还是挺简单的。但是测试一点都不简单。