JUNIT Hello World

     作为java世界大名鼎鼎的测试框架JUNIT,有着非常强大的功能,除了可以测试简单的java类以外,它还可以测试Servlet、JSP、EJB等等。下面,我们来做一个简单的HelloWorld。 

     首先,建立我们在eclipse中要测试的类;

package com.wisespotgroup.kan;

public class Calculator {

private static int result;

public void add(int m,int n){

result=n+m;

}

public void substract(int n,int m){

result=n-m;

}

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 Hello World
如果junit的bar是绿色的,就说明测试成功了
JUNIT Hello World
至此,一个简单的JUNIT测试就做好了。

你可能感兴趣的:(JUnit,测试)