做爲java世界大名鼎鼎的測試框架JUNIT,有着很是強大的功能,除了能夠測試簡單的java類之外,它還能夠測試Servlet、JSP、EJB等等。下面,咱們來作一個簡單的HelloWorld。 java
首先,創建咱們在eclipse中要測試的類;框架
package com.wisespotgroup.kan;eclipse
public class Calculator { ide
private static int result;測試
public void add(int m,int n){spa
result=n+m;rest
}ip
public void substract(int n,int m){get
result=n-m;it
}
public void multiply(int n,int m){
result = n*m;
}
public void divide(int n,int m){
result = n/m;
}
public void square(int n,int m){
result = n%m;
}
public void squareRoot(int n){
for(;;);
}
public void clear(){
result = 0;
}
public int getResult(){
return result;
}
}
而後,搭建測試環境,我會用到hamcrest的方法,因此要引入這個jar包(引入以下jar包)
寫測試代碼:
package com.wisespotgroup.kan;
import static org.junit.Assert.fail;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import static org.junit.Assert.*;
import static org.hamcrest.Matchers.*;
import org.junit.Test;
public class CalculatorTest {
private Calculator cal = new Calculator();
public void setUp() throws Exception{
cal.clear();
}
@Test
public void testAdd() {
cal.add(2, 3);
Assert.assertEquals("Exception in add() method!", 5, cal.getResult());
}
@Test
public void testSubstract() {
cal.substract(8, 4);
Assert.assertEquals("Exception in substract() method", 4, cal.getResult());
}
@Test
public void testMultiply() {
cal.multiply(7, 8);
Assert.assertEquals("Exception in mutiply() method", 56, cal.getResult());
}
@Test
public void testDivide() {
cal.divide(81, 9);
Assert.assertThat(cal.getResult(),greaterThan(3));
Assert.assertEquals(9,cal.getResult());
}
@Test
public void testSquare() {
cal.square(7, 2);
Assert.assertEquals(1,cal.getResult());
}
@Test
@Ignore
public void testSquareRoot() {
fail("Not yet implemented");
}
@Test
public void testClear() {
cal.clear();
Assert.assertThat("Hamcrest Exception!",cal.getResult(), is(not(2)));
Assert.assertEquals(0,cal.getResult());
}
}
在JUNIT4之後,對於測試方法的命名就沒什麼要求了,只要在測試方法上加:@Test便可。
語句 Assert.assertEquals(9,cal.getResult()); 就斷言9和cal.getResult()的值是同樣的
語句 Assert.assertThat("Hamcrest Exception!",cal.getResult(), is(not(2))); 就是說,我判斷cal.getResult()的值不是2;若是是2的話,異常就顯示"Hamcrest Exception!"。
最後,在eclipse中執行測試方法:
若是junit的bar是綠色的,就說明測試成功了
至此,一個簡單的JUNIT測試就作好了。