We will learn how to install Junit, Hamcrest and Eclemma.
1.Build a new project: this project include two source folder--src and test, src is source code and test is test code.
2.Click the project with the right button, select properties ->Java Build Path ->Libraries->Add external JARs(Junit(4.12) and Hamcrest(1.3) have already download):
3.Install Eclemma:
Click help->Eclipse Marketplace->search Eclemma->install, and then you will see this button:
4.Write a test code,the code is about deciding what triangle the triangle is, including equilateral triangle, isosceles triangle and scalene triangle.
package com.lab1; public class Triangle { public int a; public int b; public int c; Triangle(){ a=1; b=1; c=1; } Triangle(int a1, int b1, int c1){ if(a1+b1>c1 || a1+c1>b1 || b1+c1>a1){ a=a1; b=b1; c=c1; } else System.out.println("It's not a triangle!"); } Boolean equilateral(){ if(this.a == this.b && this.b==this.c) return true; else return false; } Boolean isosceles(){ if(this.a == this.b || this.a==this.c || this.b==this.c) return true; else return false; } Boolean scalene(){ if(this.a != this.b && this.a != this.c && this.b != this.c) return true; else return false; } }
and test code:
package com.lab1; //import org.junit.Before; import org.junit.Test; // 静态导入 import static org.junit.Assert.*; public class TestTriangle { /*@Before public void setUp(){ s = new Triangle(); }*/ @Test public void testEquilateral(){ Triangle s=new Triangle(1,1,1); /* * 以下是一个简单的断言的编写 * 第一个参数是如果出错给出的提示信息 * 第二个表示期望值,通常是用户指定的内容 * 第三个表示代码返回的实际值 */ // Assert.assertEquals("Equilateral is fault", true, s.equilateral()); /* * 由于包进行了静态导入之后 * Assert中的所有静态方法就不用再添加类名了 * 这样可以有效地兼容junit3 */ assertEquals("Equilateral is fault", true, s.equilateral()); } @Test public void testIsosceles(){ Triangle s= new Triangle(2,2,3); assertEquals("Isosceles is fault", true, s.isosceles()); } @Test public void testScalene(){ Triangle s=new Triangle(2,3,4); assertEquals("Scalene is fault", true, s.scalene()); } }
5.Run the test code:
no error.
6. Click the eclemma button, we can see the coverage:
And my code test coverage is 69.9%.