一、实验名称
利用Junit测试三角形的形状
二、实验内容
1、在IDEA中导入Junit和Hamcrest。
2、在IDEA中导入Eclemma。
3、编写判断三角形形状的程序并测试。
三、实验步骤
1、在IDEA中新建工程。
2、在工程下添加lib文件夹,把Junit、Hamcrest和Eclemma的jar包拷入文件夹。并将它设置为lib路径。
3、新建test文件夹并将其设置为测试的根目录。
4、在src文件夹下新建java类命名为Triangle,在test文件夹下新建java类命名为TriangleTest。
5、编写代码和测试用例。
6、通过TriangleTest来运行程序。
四、实验代码与实验结果
Trianle.java
/**
* Created by luvian on 16/3/18.
*/
public class Triangle {
private String side1;
private String side2;
private String side3;
public Triangle() {
this("0", "0", "0");
}
public Triangle(String s1, String s2, String s3) {
this.side1 = s1;
this.side2 = s2;
this.side3 = s3;
}
public String determineTriangleType() {
String type = "";
int s1 = -1, s2 = -1, s3 = -1;
String err = "";
try {
s1 = Integer.parseInt(side1);
} catch (NumberFormatException e) {
err += "Side 1 is not a number!\n";
}
try {
s2 = Integer.parseInt(side2);
} catch (NumberFormatException e) {
err += "Side 2 is not a number!\n";
}
try {
s3 = Integer.parseInt(side3);
} catch (NumberFormatException e) {
err += "Side 3 is not a number!\n";
}
if (s1 <= 0 || s2 <= 0 || s3 <= 0) {
err += "Please enter three positive numbers!\n";
}
if ((s1 + s2 <= s3) || (s1 + s3 <= s2) || (s2 + s3 <= s1)) {
err += "Cannot make a triangle!\n";
}
if (s1 + s2 + s3 > 1000000) {
err += "The triangle is too big\n";
}
if (err.length() > 0) {
type = err;
} else {
if ((s1 == s2) && (s2 == s3) && (s1 == s3)) {
type = "Isosceles";
} else if ((s1 == s3) && (s2 == s3)) {
type = "Equilateral";
} else {
type = "Scalene";
}
}
return type;
}
}
TrianleTest.java
import org.junit.Test;
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import static junit.framework.TestCase.fail;
import static org.junit.Assert.*;
/**
* Created by luvian on 16/3/18.
*/
public class TriangleTest {
@Test
public void test() {
Set<String>typeSet = new HashSet<String> ();
typeSet.add("Equilateral");
typeSet.add("Isosceles");
typeSet.add("Scalene");
Triangle t1 = new Triangle("a", "b", "c");
String type1 = t1.determineTriangleType();
if(typeSet.contains(type1)){
fail("error of type");
}
Triangle t2 = new Triangle("1", "1", "1");
String type2 = t2.determineTriangleType();
if(!typeSet.contains(type2)){
fail("error of type");
}
assertEquals("Isosceles", type2);
}
}