Lab 1 Junit and Eclemma
Tasks:
- 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.
a) 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.
Solutions:
1. installation:
a) Firstly, open a java project, enter the 'Java Build Path' menu, then click button 'Add External JARs', choose Junit and Hamcrest JARs which I have downloaded from a website somewhere, then the plugins will be successfully imported.
b) Open Eclipse Marketplace, in which you can search Eclemma plugin, then install it. After a restart of Eclipse, the Eclemma plugin has been successfully intalled.
2. Triangle Problem:
Triangle.java (Original Code)
package sjh;
public class triangle {
public double a, b, c;
public triangle(){
this.a = 1;
this.b = 1;
this.c = 1;
}
public void setSide(double a, double b, double c){
this.a = a;
this.b = b;
this.c = c;
try{
if(a>0&&b>0&&c>0&&a+b>c&&b+c>a&&a+c>b){
//nothing will happen
}
else{
//not a triangle
throw new Exception();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public boolean ifEquilateral(){
if(a == b && b == c){
return true;
}
else {
return false;
}
}
public boolean ifIsosceles(){
if(a == b || b == c || a == c){
return true;
}
else {
return false;
}
}
public boolean ifScalene(){
if(a != b && b != c && a != c){
return true;
}
else {
return false;
}
}
}
TriangleTest.java (Testing Code)
package sjh;
import static org.junit.Assert.*;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class triangleTest {
private static triangle tri = new triangle();
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testIfEquilateral() {
tri.setSide(1.0, 1.0, 1.0);
assertEquals(tri.ifEquilateral(), true);
}
@Test
public void testIfIsosceles() {
tri.setSide(1.5, 2.0, 2.0);
assertEquals(tri.ifIsosceles(), true);
}
@Test
public void testIfScalene() {
tri.setSide(1.0, 1.5, 2.0);
assertEquals(tri.ifScalene(), true);
}
}
The testing code tests 3 functions from the original one, IfEquilateral(), IfIsosceles() and IfScalene().
Then we will get:
And
This means we've made a success.