junit4中annotation的几种应用

本文介绍了使用Java实现数学运算类及其对应的单元测试方法,包括加法和除法操作,并通过断言验证了方法的正确性。此外,还演示了如何处理除数为零的异常情况,以及设置超时时间来确保测试的效率。
package com.fsti.math;

public class MathDemo {
	
	public int add(int a, int b) {
		return a + b;
	}
	
	public int div(int a, int b) {
		if (b == 0) {
			throw new ArithmeticException("除数不能为0!");
		}
		return a / b;
	}
}

package com.fsti.math;

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

public class MathDemoTest {
	MathDemo md = null;	
	
	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
		System.out.println("setUpBeforeClass......");
	}

	@AfterClass
	public static void tearDownAfterClass() throws Exception {
		System.out.println("tearDownAfterClass......");
	}
	
	@Before
	public void setUp() throws Exception {
		System.out.println("SetUp...");
		md = new MathDemo();
	}

	@After
	public void tearDown() throws Exception {
		System.out.println("TearDown...");
		md = null;
	}
	
	@Test
	public void testAdd() {
		int expected = 3;
		int actual = md.add(1, 2);
		assertEquals(expected, actual);
	}
	
	@Test
	public void testDiv() {
		int expected = 3;
		int actual = md.div(6, 2);
		assertEquals(expected, actual);
	}
	
	@Test(expected=ArithmeticException.class)
	public void testDivWithZero() {
		int expected = 3;
		int actual = md.div(6, 0);
		assertEquals(expected, actual);
	}

	@Test(timeout=100)
	public void testDivWithTimeout() {
		int expected = 3;
		int actual = md.div(6, 2);
		assertEquals(expected, actual);
	}
	
	@Test
	@Ignore
	public void testIgnore() {
		assertEquals(1, 1);
	}
}
执行的结果如下图:
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值