JUNIT 入门2(语法及应用)

          本文主要介绍JUNIT 语法及常用函数应用。

一、       常用annotation

@Before:初始化方法,在任何一个测试执行之前必须执行的代;

@After源,在任何测试执行之后需要行的收尾工作。在每个测试方法行之后行一次,annotation只能修public void 方法;

@Test测试方法,表明是一个测试方法。在Junit中将会自行。annotation只你呢个修public void 方法。于方法的声明也有如下要求:名字可以随便取,没有任何限制,但是返回须为void,而且不能有任何参数。如果定,会在运行抛出一个异常。至于方法内写些什么,那就要看你需要测试些什么了;里可以测试期望异常和超时时间,如 @Test(timeout = 100):我们给测试函数定一个时间,超时间(100毫秒),它就会被系统强止,并且系统还会向你汇报该函数束的原因是因这样你就可以发现这Bug了。

@Ignore:忽略的测试方法,注的含就是某些方法尚未完成,不参与此次测试”;这样话测试结果就会提示你有几个测试被忽略,而不是失。一旦你完成了相函数,只需要把@Ignore去,就可以行正常的测试

@BeforeClass针对所有测试,只行一次,且必须为public static void;

@AfterClass针对所有测试,将会在所有测试方法束后行一次,且必须为public static void;

所以一个Junit 4 测试用例@BeforeClass –> @Before –> @Test –> @After –> @AfterClass;每一个测试方法的@Before –> @Test –> @After

二.例子

package com.learn;

import static org.junit.Assert.*;
import org.junit.*;

public class JunitLearn {
    @Test
    public void testHello() {
        assertEquals("they are not equal.",(new HelloEntity().hello()), "hello1");
        System.out.println("@testHello");
    }

    @Before
    public void before() {

        System.out.println("@Before");

    }

    @Test
    public void test() {

        System.out.println("@Test");

        assertEquals(5 + 5, 10);

    }

    @Ignore
    @Test
    public void testIgnore() {

        System.out.println("@Ignore");

    }

    @Test(timeout = 50)
    public void testTimeout() {

        System.out.println("@Test(timeout = 50)");

        assertEquals(5 + 5, 10);

    }

    @Test(expected = ArithmeticException.class)
    public void testExpected() {

        System.out.println("@Test(expected = Exception.class)");

        throw new ArithmeticException();

    }

    @After
    public void after() {
        System.out.println("@After");
    }

    @BeforeClass
    public static void beforeClass() {

        System.out.println("@BeforeClass");

    };

    @AfterClass
    public static void afterClass() {

        System.out.println("@AfterClass");

    };
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值