import static org.junit.Assert.*; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class TriangleTest { @BeforeClass public static void setUpBeforeClass() throws Exception { } @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testCheck() { assertEquals( Triangle.check(1,1,1) , 1 ); assertEquals( Triangle.check(2,2,3) , 2 ); assertEquals( Triangle.check(2,3,4) , 3 ); assertEquals( Triangle.check(1,1,3) , -1 ); } }
二.实验过程
1.JUnit、Hamcrest的安装:
1)从网上下载junit-4.12.jar 和 hamcrest-all-1.3.jar文件。
2)在Eclipse中新建项目 (File - new - javaproject)
右键点击项目,选择Build Path - Configure Build Path
然后点击Libraries - Add External JARs,选择jar包打开,确认
2.Eclemma的安装:
在菜单栏选择Help - Eclipse Marketplace,搜索Eclemma,点击Install安装,重启Eclipse
Triangle Problem
import java.util.Scanner; public class Triangle { public static final int equilateral= 1; public static final int isosceles= 2; public static final int scalene= 3; public static int check(int a,int b,int c){ if(a+b>c&&a+c>b&&b+c>a){ if(a==b&&b==c) return equilateral; //equilateral else if(a==b||b==c||a==c) return isosceles; //isosceles else return scalene; //scalene } else return -1; } }
Junit test
import static org.junit.Assert.*; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; public class TriangleTest { @BeforeClass public static void setUpBeforeClass() throws Exception { } @AfterClass public static void tearDownAfterClass() throws Exception { } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } @Test public void testCheck() { assertEquals( Triangle.check(1,1,1) , 1 ); assertEquals( Triangle.check(2,2,3) , 2 ); assertEquals( Triangle.check(2,3,4) , 3 ); assertEquals( Triangle.check(1,1,3) , -1 ); } }