junit3 对比 junit4

Life is short , play more!
本文来自lihao's Blog,转载请注明。

Junit3 和 junit4 到底有什么区别呢? 我们到底该使用junit3 还是 junit4 !

一.  junit4 不需要testcase的方法前必须加test标识

junit3 代码示例

import junit.framework.TestCase;

public class MayorTest extends TestCase

{

public void testOrden() {…}

}

junit4 代码示例

import org.junit.Test;

import junit.framework.TestCase;

public class MayorTest extends TestCase {…

@Test public void miTestOrden() {…}

}

junit4中自定义testcase方法名称,无需test开头了。 看着也方便舒心。

junit4中也不再需要extend testcase。

import static org.junit.Assert.*;

public class MayorTest {

@Test public void primerTestOrden() { …}

}

二  assert 异常

junit3中代码示例

public void testVacia()

{

try

{

Ejemplo.calcularMayor(new int[] {});

fail(“Should have thrown an exception”);

} catch (RuntimeException e) {…}

}

junit4中代码

@Test(expected=RuntimeException.class)

public void testVacia()

{

Ejemplo.calcularMayor(new int[] {});

}

三、 测试用例timeout 时间设定junit4新功能

如果case执行时间超过设定的timeout时间,则timeout并失败

@Test(timeout=500)

public void testRecuperarDatos()

{ … }

四、如何ignore掉用例,比如废弃的用例等。junit4 新功能

@Ignore public void testMuylento()

{ … }

五、用例初始化

junit3 中只提供了 setup 和 teardown 方法,在每一个测试用例前后运行。

junit4 提供了更多,且可以自定义初始化的方法名称。

@Before
public void method()
This method is executed before each test. This method can prepare the test environment (e.g. read input data, initialize the class).
@After
public void method()
This method is executed after each test. This method can cleanup the test environment (e.g. delete temporary data, restore defaults). It can also save memory by cleaning up expensive memory structures.
@BeforeClass
public static void method()
This method is executed once, before the start of all tests. This can be used to perform time intensive activities, for example to connect to a database. Methods annotated with this annotation need to be defined as static to work with JUnit.
@AfterClass
public static void method()
This method is executed once, after all tests have been finished. This can be used to perform clean-up activities, for example to disconnect from a database. Methods annotated with this annotation need to be defined as static to work with JUnit.


发表评论

电子邮件地址不会被公开。 必填项已用*标注