1、Install Junit(4.12), Hamcrest(1.3) with Eclipse
2、Install Eclemma with Eclipse
3、Write a java program for the triangle problem and test the program with Junit.
Description of triangle problem:
Function triangle takes three integers a,b,c which are length of triangle sides; calculates whether the triangle is equilateral, isosceles, or scalene.
Triangle.java:
1 package cn.st.lab1; 2 3 public class Triangle { 4 public static boolean isTriangle(int a, int b, int c) { 5 if(a+b>c && a+c>b && b+c>a && Math.abs(a-b)<c && 6 Math.abs(a-c)<b && Math.abs(b-c)<a && a>0 && b>0 && c>0) { 7 return true; 8 } 9 else { 10 return false; 11 } 12 } 13 public static boolean isEquilateral(int a, int b, int c) { 14 if(isTriangle(a,b,c)) { 15 if(a == b && a == c) { 16 return true; 17 } 18 } 19 return false; 20 } 21 public static boolean isIsosceles(int a, int b, int c) { 22 if(isTriangle(a,b,c)) { 23 if(a == b || a == c || b == c) { 24 return true; 25 } 26 } 27 return false; 28 } 29 30 public static void Triangle (int a, int b, int c) { 31 if(isTriangle(a,b,c)) { //输出以下内容,则为三角形 32 if(isEquilateral(a,b,c)) { 33 System.out.println("Equilateral"); 34 } //如果是等边,只输出等边,不输出等腰 35 else if(isIsosceles(a,b,c)) { 36 System.out.println("Isosceles"); 37 } 38 else { 39 System.out.println("Scalene"); 40 } 41 } 42 else { 43 System.out.println("NotATriangle"); 44 } 45 } 46
testTriangle.java:
1 package cn.st.lab1; 2 3 import static org.junit.Assert.*; 4 5 import org.junit.*; 6 7 public class testTriangle { 8 9 Triangle t; 10 @Before 11 public void setUp(){ 12 t = new Triangle(); 13 } 14 15 @Test 16 public void testIsEquilateral() { 17 assertEquals("testIsEquilateral", true, t.isEquilateral(6,6,6)); 18 } 19 @Test 20 public void testIsIsosceles() { 21 assertEquals("testIsIsosceles", true, t.isIsosceles(5,6,6)); 22 } 23 @Test 24 public void testIsTriangle() { 25 assertEquals("testIsTriangle", true, t.isTriangle(5,6,7)); 26 } 27 @Test 28 public void testTriangle() { 29 t.Triangle(3, 4, 5); 30 t.Triangle(3, 4, 4); 31 t.Triangle(4, 4, 4); 32 t.Triangle(1, 1, 5); 33 } 34 }
实验结果:
代码请见github:https://github.com/fogmisty/SoftwareTest