使用Eclipse和JUnit开发简单的单元测试

使用Eclipse和JUnit开发简单的单元测试

主要内容

编写测试报告,写出用Eclipse和JUnit开发单元测试的一般步骤、测试代码以及测试结果的屏幕截图。

步骤

在Eclipse中创建一个新的Java项目


public class Calculator {
	public int evaluate(String expression) {
		int sum = 0;
		for (String summand: expression.split("\\ +"))
			sum += Integer.valueOf(summand);
		return sum;
		
	}
}

右击Calculator.java项目,再单击弹出的快捷菜单中New→JUnit Test Case菜单项。进入如图界面:
在这里插入图片描述在这里插入图片描述
单击Finish按钮并单击OK按钮
在这里插入图片描述
Eclipse生成的CalculatorTest.java文件如下

import static org.junit.jupiter.api.Assertions.*;

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

class CalculatorTest {

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
	}

	@AfterClass
	public static void setUpAfterClass() throws Exception {
	}
	
	@Before
	public void setUp() throws Exception {
	}

	@After
	public void tearDown() throws Exception {
	}
	
	@Test
	final void test() {
		fail("Not yet implemented"); // TODO
	}

}

修改CalculatorTest文件如下

import static org.junit.jupiter.api.Assertions.*;

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

class CalculatorTest {

	@BeforeClass
	public static void setUpBeforeClass() throws Exception {
	}

	@AfterClass
	public static void setUpAfterClass() throws Exception {
	}
	
	@Before
	public void setUp() throws Exception {
	}

	@After
	public void tearDown() throws Exception {
	}
	
	@Test
	final void test() {
		Calculator calculator = new Calculator();
		int sum = calculator.evaluate("1+2+3");
		assertEquals(6,sum);
	}

}

右击Test4,在菜单中单击Build Path →Configure Build Path菜单项,进入如图所示界面
在这里插入图片描述
可以看出,该项目已添加JUnit5库文件

右击CalculatorTest .java文件,在弹出框中单击Run As →JUnit Test菜单项,执行JUnit测试用例,进入如图界面
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值