JUnit 4的一分钟介绍

【声明】一篇很好的迅速上手的JUnit教程,翻译自http://www.cavdar.net/2008/07/21/junit-4-in-60-seconds/

1. @Test
用@Test来标注你的测试用例,则不用将你的测试方法加上"test"前缀,也不用拿你的测试类去继承"TestCase"类。

    @Test
    public void addition() {
        assertEquals(12, simpleMath.add(7, 5));
    }

    @Test
    public void subtraction() {
        assertEquals(9, simpleMath.substract(12, 3));
    }


2. @Before和@After
用@Before和@After标注方式,可以分别取代"setup"和"tearDown"方法。它们将在所有测试用例之前和之后运行。

    @Before
    public void runBeforeEveryTest() {
        simpleMath = new SimpleMath();
    }

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


3. @BeforeClass和@AfterClass
@BeforeClass和@AfterClass标注则分别相当于类级别的"setup"和"tearDown",可以把它们认为是一次性的setup和tearDown。它们将分别在所有测试用例运行之前、之后运行一次。

    @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. 异常处理
使用带"expected"参数的@Test标注可以测试是否抛出异常,并且可以在参数中标明可能会抛出的异常。

    @Test(expected = ArithmeticException.class)
    public void divisionWithException() {
        // divide by zero
        simpleMath.divide(1, 0);
    }


5. @Ignore
@Ignore可以用来标明那些你想忽略的测试用例,并且还可以加上一个字符串的参数,以此来标明你想略过的原因。

    @Ignore("Not Ready to Run")
    @Test
    public void multiplication() {
        assertEquals(15, simpleMath.multiply(3, 5));
    }


6. 超时测试
可以用"timeout"参数来定义一个以毫秒计算的超时的时限,如果测试时间超过这个时限,将表示测试失败。

    @Test(timeout = 1000)
    public void infinity() {
        while (true)
            ;
    }


7. 新引入的断言(Assertion)
新的版本支持两个对象的序列的对比。如果两个序列的长度相等,并且序列中的每个相同位置元素都相等,那么就认为这两个序列是相等的,否则被认为不相等。

    @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
JUnit4TestAdapter类则可以让JUnit 4版本的类运行在JUnit 3环境下。

    public static junit.framework.Test suite() {
        return new JUnit4TestAdapter(SimpleMathTest.class);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值