Eclipse下JUnit单元测试的简单使用

最近的软件构造实验课需要用到JUnit单元测试工具,在网上查找了一些资料,自己尝试着试验了一下,觉得有必要把简单的使用过程记录下来。

工具:Eclipse

第一步:新建一个文件File-new-Java project

第二步:完成之后,在src下创建两个包,一个存放被测试代码,另一个存放测试代码,这里分别是exercise1和test

被测试代码选用一个计算h-index的程序(是一道leetcode题目,写的不好请见谅) 

package exercise1;

import java.util.Arrays;
import java.util.Scanner;

public class Solution {

	public static int hIndex(int[] citations) {
		int n = citations.length;//论文总数
		//统计各引用次数对应的论文数,大于n次的计为n
		int[] count = new int[n+1];
		Arrays.fill(count, 0);
		for(int c:citations) {
			if(c>=n)
				count[n]++;
			else
				count[c]++;
		}
		//获得最大的h指数
		int h = n,c = count[n];//当前h值,引用不小于h的论文数量
		while(c<h)
			c+=count[--h];
		return h;
	}
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);
		System.out.println("请输入论文数量:");
		int n = in.nextInt();
		int[] citations = new int[n];
		System.out.println("请输入每篇论文被引量:");
		for(int i=0;i<n;i++) {
			citations[i] = in.nextInt();
		}
		System.out.println("the h-Index is:"+hIndex(citations));
		in.close();
	}

}

 第三步:编写好代码之后,右键项目-build path-add libraries-选里面的JUnit,然后next

这里可以选择JUnit类型,在这里使用JUnit4 ,然后finish即可

 第四步:在test包(测试包)右键-new-JUnit Test Case

 添加测试类的名字(可以自定义),以及被测试类的名字(确保能找到,找不到会显示)

 然后next,选择被测试的函数,这里只选择选择HIndex,然后finish

 第五步:可以看到新创建的class文件

 在fail这一行输入自己的测试代码,assertEquals函数是判断用户给定的正确答案与被测试函数的答案是否一致的,这里正确答案应当是3

package test;

import static org.junit.Assert.*;

import org.junit.Test;

import exercise1.Solution;

public class TestJUnit {

	@Test
	public void testHIndex() {
		int[] citations = {3,0,6,1,5};
		assertEquals(3,Solution.hIndex(citations));
	}
}

第六步:在 TestJUnit这个class右键-run as-JUnit Test,可以看到测试成功啦

 

 水平有限,错误之处希望指出~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值