Junit 4 与Junit3 区别 及使用

1. @Test
在JUnit3,所有的test case的方法名都要以"test"为前缀prefix;
在JUnit4,在test case的方法前加上@Test,就明白了。
@Test
public void empty() {
/* test case 1*/
Collection collection = new ArrarList();
assertTrue(collection.isEmpty());
}

2. @Before 和 @After
@Before 和 @After 就是setUp()和tearDown()的替代。
@Before
public void runBeforeEveryTest() {
simpleMath = new SimpleMath();
}

@After
public void runAfterEveryTest() {
simpleMath = null;
}

3. @BeforeClass 和 @AfterClass
在JUnit3,如果想仅调用一次setUp()和tearDown() for all test cases, 使用TestSetup类;在JUnit4,就省事了:
@BeforeClass
public static void runBeforeClass() {
// run for one time before all test cases
}

@AfterClass
public static void runAfterClass() {
// run for one time after all test cases
}

4. 测试异常处理
在《JUnit3的使用》文章中,看到旧式的异常测试是在抛出异常的代码中放入 try 块,然后在 try 块的末尾加入一个 fail() 语句:
public void testCase2() {
/* test case 2*/
ArrayList emptyList = new ArrayList();
try {
Object o = emptyList.get(0);
fail("Should raise an IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException expected) {
assertTrue(true);
}
}
在JUnit4,添加@Test,使用参数“expected”,并指明抛出异常的Exception类:
@Test(expected = IndexOutOfBoundsException.class)
public void testCase2() {
/* test case 2*/
ArrayList emptyList = new ArrayList();
Object o = emptyList.get(0);
}

5. @Ignore
对于你想暂时不进行的test cse, 在该方法前添加@Ignore
@Ignore("Not Ready to Run")
@Test
public void multiplication() {
assertEquals(15, simpleMath.multiply(3, 5));
}

6. 设置超时
在@Test,使用"timeout"参数。如果测试运行的时间超过指定的毫秒数,则测试失败。
@Test(timeout=3000)
public void remoteBaseRelativeResolutionWithDirectory()
 throws IOException, ParsingException {
  readBuilder.parse("config.xml");
}

7.添加了新的断言
JUnit 4 为比较数组添加了两个 assert() 方法:
  public static void assertEquals(Object[] expected, Object[] actual)
public static void assertEquals(String message, Object[] expected, Object[] actual)
  这两个方法以最直接的方式比较数组:如果数组长度相同,且每个对应的元素相同,则两个数组相等,否则不相等。数组为空的情况也作了考虑。
@Test
public void listEquality() {
List<Integer> expected = new ArrayList<Integer>();
expected.add(5);

List<Integer> actual = new ArrayList<Integer>();
actual.add(5);

assertEquals(expected, actual);
}

8. JUnit4Adapter
为了能够在JUnit3环境下run JUnit4 test, 所以提供了JUnit4Adapter
public static junit.framework.Test suite() {
return new JUnit4TestAdapter(SimpleMathTest.class);
}

9.其他
失败(assert 方法检测到的预期的错误)与错误(异常指出的非预期的错误)之间不再有任何差别。尽管 JUnit 3 测试运行程序仍然可以区别这些情况,而 JUnit 4 运行程序将不再能够区分。


转自博客:http://android.blog.51cto.com/268543/50979
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值