在Eclipse中使用Junit

1、准备测试类

java 复制代码
public class Calculator {
	private static int result;
	public void add(int n) {
		result = result + n;
		}	
	public void substract(int n) {
		result = result -1; //Bug:正确的应该是result=result-n
	}
	public void multiply(int n) {
		// result = result*n;方法未写好
	}
	public void divide (int n) {
		result = result/n;
	}
	public void squre(int n) {
		result = n * n;
	}
	public void squareRoot(int n) {
		for(;;)
			;//Bug:死循环
	}
	public void clear() {
		result = 0;
	}	
	public int getResult() {
		return result;
	}
}

2、引入Junit测试包

此时Junit包已经加载在项目下

3、构建Junit框架

这样就构建test包,一般test包和src源码包分别放在不同的文件夹中。

创建Junit测试类

就会生成一个默认的测试框架

最后对测试框架进行简单的编写

java 复制代码
import static org.junit.Assert.*;

import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

public class TestCaculator {
	private static Calculator calcultor = new Calculator();
	
	@Before
	public void setUp() throws Exception {
		calcultor.clear();
	}

	@Test
	public void testAdd() {
		calcultor.add(2);
		calcultor.add(3);
		assertEquals(5, calcultor.getResult());
	}

	@Test
	public void testSubstract() {
		calcultor.add(10);
		calcultor.substract(2);//因为每次运行测试方法前,都会运行setUp()进行清空,所以互不影响
		assertEquals(8, calcultor.getResult());
	}

	@Ignore("Mutiply not yet implemented")
	@Test
	public void testMultiply() {
		
	}

	@Test
	public void testDivide() {
		calcultor.add(10);
		calcultor.divide(5);
		assertEquals(2, calcultor.getResult());
	}

}

这就是Junit4在eclipse中的测试用例编写和运行的过程

相关推荐
小短腿的代码世界4 小时前
Qt 股票订单撮合引擎:高频交易系统的核心心脏
开发语言·数据库·qt·系统架构·交互
JosieBook5 小时前
【数据库】时序数据库选型指南:从数据模型到大模型智能分析
数据库·时序数据库
小猿姐6 小时前
Clickhouse Kubernetes Operator 实测:哪种方案更适合生产?
运维·数据库·kubernetes
2501_921939266 小时前
MHA高可用
数据库·mysql
_Evan_Yao6 小时前
MySQL 基础:SELECT、WHERE、JOIN 的第一次使用
数据库·mysql
weixin_444012937 小时前
c++如何将std--vector直接DUMP到二进制文件_指针地址直写【附代码】
jvm·数据库·python
woxihuan1234567 小时前
Go语言中--=运算符详解:位右移赋值操作的原理与应用
jvm·数据库·python
java1234_小锋7 小时前
SpringBoot为什么要禁止循环依赖?
java·数据库·spring boot
神仙别闹8 小时前
基于QT(C++)实现学生成绩管理系统
数据库·c++·qt
m0_690825828 小时前
如何备份被破坏的数据表_强制跳过错误的导出尝试
jvm·数据库·python