您的位置:首页 > 其它

学习使用junit进行单元测试,

2015-07-18 23:58 477 查看
使用junit4 进行单元测试,记录如下,

测试代码如下:

测试类,计算加法和减法:

public class Calc {

public int plus(int one,int two){
return one+two;
}
public int minus(int one,int two){
return one-two;
}

}

测试类如下:

import static org.junit.Assert.*;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

/**
*
*/
public class CalcTest {

/**
* beforeclass,必须是静态void类型,只会执行一次
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass() throws Exception {
System.out.println("i'm in beforeclass");
}
/**
* beforeclass,必须是静态void类型, 只会执行一次
* @throws java.lang.Exception
*/
@BeforeClass
public static void setUpBeforeClass1() throws Exception {
System.out.println("i'm in beforeclass1");
}

/**
* 必须是静态void类型, 只会执行一次
* @throws java.lang.Exception
*/
@AfterClass
public static void tearDownAfterClass() throws Exception {
System.out.println("i'm in afterclass");
}

/**
* 每个测试方法之前都会执行
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {

System.out.println("i'm in before");
}
/**
* 每个测试方法之前都会执行
* @throws Exception
*/
@Before
public void setUp2() throws Exception {

System.out.println("i'm in before2");
}

/**
* 每个测试方法之后都会执行
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
System.out.println("i'm in after");
}

/**
* 具体的测试方法,timeout,要求方法必须在多少时间内完成,单位纳秒
*
* Test method for {@link org.daipl.junit.Calc#plus(int, int)}.
*/
@Test(timeout=6)
public void testPlus() {
Calc calc=new Calc();
assertEquals(6, calc.plus(2, 3));
}
/**
* 测试加法
* Test method for {@link org.daipl.junit.Calc#plus(int, int)}.
*/
@Test()
public void testPlus2() {
Calc calc=new Calc();
assertEquals(6, calc.plus(2, 3));
}

/**
* 测试抛出的异常信息,
* 如果结果不对,assertEquals会抛出AssertionError,所以判断的异常需要考虑这点
* Test method for {@link org.daipl.junit.Calc#minus(int, int)}.
* @throws Exception
*/
@Test(expected=NullPointerException.class)
public void testMinus() throws Ex
4000
ception {
Calc calc=new Calc();

assertEquals(51, calc.minus(8, 3));
throw new NullPointerException();
}
/**
* 测试计算结果
* Test method for {@link org.daipl.junit.Calc#minus(int, int)}.
* @throws Exception
*/
@Test
public void testMinus2() throws Exception {
Calc calc=new Calc();

assertEquals(5, calc.minus(8, 3));
}

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