实验环境:Mac + IDEA + junit-4.12 + hamcrest-core-1.3
首先安装 Junit(测试) 和 Hamcrest(测试覆盖)
下载地址:https://github.com/junit-team/junit4/wiki/Download-and-Install
需要下载两个 jar 包:junit-4.12.jar 和 hamcrest-core-1.3.jar
首先建立项目 Lab1
填写项目名称和项目路径
然后创建一个 JavaClass :Triangle
编写代码:
/**
* Created by yuchunyu97 on 2018/3/22.
*/
public class Triangle {
private int one;
private int two;
private int three;
public static boolean isLegal(int len1, int len2, int len3) {
if (len1 <= 0 || len2 <= 0 || len3 <= 0)
return false;
if (len1 + len2 > len3 && len2 + len3 > len1 && len1 + len3 > len2)
return true;
return false;
}
public Triangle(int side_1, int side_2, int side_3) {
if (isLegal(side_1, side_2, side_3)) {
one = side_1;
two = side_2;
three = side_3;
} else
one = two = three = 1;
}
public boolean isEquilatera() {
// 等边三角形
return (one == two && one == three);
}
public boolean isIsosceles() {
// 等腰三角形
return (one == two || one == three || two == three);
}
public boolean isScalene() {
// 不等边三角形;
return !isEquilatera();
}
}
然后创建测试用例
使用快捷键:Command + Shift + T
填写相应的设置信息
在写测试代码之前,需要先引用之前下好的两个 jar 包
新建一个目录 lib
将两个 jar 包拷贝dao到 lib 目录下
然后点击 File - Project Structure - Libraries - +
从 lib 目录下将两个 jar 包引入
点 OK 保存
然后编写测试代码
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Created by yuchunyu97 on 2018/3/22.
*/
public class TriangleTest {
private Triangle tri1;
private Triangle tri2;
private Triangle tri3;
private Triangle tri4;
@Before
public void setUp() throws Exception {
tri1 = new Triangle(3, 3, 3);
tri2 = new Triangle(3, 3, 5);
tri3 = new Triangle(3, 4, 5);
tri4 = new Triangle(-3, 4, 5);
}
@Test
public void isEquilatera() throws Exception {
// 等边三角形
assertTrue(tri1.isEquilatera());
}
@Test
public void isIsosceles() throws Exception {
// 等腰三角形
assertTrue(tri2.isIsosceles());
}
@Test
public void isScalene() throws Exception {
// 不等边三角形
assertTrue(tri3.isScalene());
assertTrue(tri4.isScalene());
}
}
然后进行测试
点击运行按钮下的:Run ‘TriangleTest‘ with Coverage
就可以看到测试的结果了