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


使用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 Exception {
		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));
	}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值