您的位置:首页 > 其它

Junit的简单使用

2014-11-30 20:51 288 查看
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;

/**
* 执行任意一个方法之前都会执行这个方法
*/
@Before
public void setUp(){
cal = new Calculate();
}

/**
* 要测试的方法,断言第二个参数是期望值,第三个是实际值
*/
@Test
public void testAdd(){
int res = cal.add(10, 20);
assertEquals("加法有问题", res, 30);
}
@Test
public void testSub(){
int res = cal.sub(10, 20);
assertEquals("减法有问题", res, -10);
}
@Test
public void testMul(){
int res = cal.mul(10, 20);
assertEquals("乘法有问题", res, 200);
}
@Test
public 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 block
e.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;
}

@Parameters
public static Collection data(){
return Arrays.asList(new Object[][]{
{2,4},{0,0},{-3,9}
});
}

@Test
public 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 {

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: