Junit的简单使用

来源:互联网 发布:游戏人生软件下载 编辑:程序博客网 时间:2024/05/21 17:15

Junit的简单使用,当然首先要引入Junit.jar包,然后导入。


@Test要测试的方法testAdd()

@Test(expected=ArithmeticException.class)抛出异常testDivideException()

@Test(timeout=300)超时time()

@Before在所有测试方法执行之前固定要执行的方法setUp()

@After在所有测试方法执行之后固定要执行的方法tearDown()

@RunWith(Parameterized.class)类的参数化测试,在类开始前

@Parameters初始化参数,对应着构造方法

打包测试(写在类前,包含所要测试的类):

@RunWith(Suite.class)
@Suite.SuiteClasses({TestCalculate.class,ParamTest.class})

public class Calculate {public int add(int a,int b){return a+b;}public int sub(int a,int b){return a-b;}public int mul(int a,int b){return a*b;}public int div(int a,int b){return a/b;}public int square(int n){return n*n;}}
import static org.junit.Assert.*;import org.junit.Before;import org.junit.Test;public class TestCalculate {Calculate cal;/** * 执行任意一个方法之前都会执行这个方法 */@Beforepublic void setUp(){ cal = new Calculate();}/** * 要测试的方法,断言第二个参数是期望值,第三个是实际值  */@Testpublic void testAdd(){int res = cal.add(10, 20);assertEquals("加法有问题", res, 30);}@Testpublic void testSub(){int res = cal.sub(10, 20);assertEquals("减法有问题", res, -10);}@Testpublic void testMul(){int res = cal.mul(10, 20);assertEquals("乘法有问题", res, 200);}@Testpublic void testDiv(){int res = cal.div(10, 20);assertEquals("除法有问题", res, 0);}/** * 表示这个测试类应该抛出ArithmeticException异常,如果不抛出就报错 */@Test(expected=ArithmeticException.class)public void testDivException(){int res = cal.div(10, 0);}//表示这个方法应该在300毫秒内执行结束才算正确@Test(timeout=300)public void time(){try {Thread.sleep(200);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

import static org.junit.Assert.*;import java.util.Arrays;import java.util.Collection;import org.junit.Test;import org.junit.runner.RunWith;import org.junit.runners.Parameterized;import org.junit.runners.Parameterized.Parameters;/** * 参数测试 * @author  * */@RunWith(Parameterized.class)public class ParamTest {private static Calculate cal = new Calculate();private int param;private int result;//构造函数初始化public ParamTest(int param,int result){this.param = param;this.result = result;}@Parameterspublic static Collection data(){return Arrays.asList(new Object[][]{{2,4},{0,0},{-3,9}});}@Testpublic void testSquare(){int res = cal.square(param);assertEquals(result,res);}}

import org.junit.runner.RunWith;import org.junit.runners.Suite;/** * 打包测试,可以测试多个类 * @author  * */@RunWith(Suite.class)@Suite.SuiteClasses({TestCalculate.class,ParamTest.class})public class AllTest {}




0 0
原创粉丝点击