1.引入JUnit4类库:启动eclipse->创建一个java项目->右键项目选址“Properties”命令->选址JavaBuildPath选项->点击“Libraries”标签->点击“AddLibrary”按钮->选择“JUnit”选项->选择“JUnit4”后finish
2.java项目中编辑一个class类:Calculator类
public classCalculator {
public int result=0;
public int add(int operand1,int operand2){
result=operand1+operand2;
return result;
}
public int subtract(int operand1,int operand2){
result=operand1-operand2;
return result;
}
public int multiple(int operand1,int operand2){
result=operand1*operand2;
return result;
}
public int divide(int operand1,int operand2){
result=operand1/0;
return result;
}
public intgetResult(){
return this.result;
}
}
3.在Calculator类所在Package下创建一个JUnitTestCase:在package包右键->new->JUnitTestCase->name输入CalculatorTest,勾选“setUpBeforeClass/setUp/tearDownAfterClass/tearDown”4个复选框,并在Class under test中输入package包名.Calculator点击finish。
在生成的CalculatorTest中编辑如下代码:
public classCalculatorTest {
private staticCalculator cal=new Calculator();
@BeforeClass
public static voidsetUpBeforeClass() throws Exception {
System.out.println("BeforeClass");
}
@AfterClass
public static voidtearDownAfterClass() throws Exception {
System.out.println("AfterClass");
}
@Before
public void setUp() throws Exception{
System.out.println("Before");
}
@After
public voidtearDown() throws Exception {
System.out.println("After");
}
@Test
public void testAdd(){
cal.add(2,2);
//fail("Not yetimplemented");
assertEquals(4, cal.getResult());
}
@Test
public voidtestSubstract(){
cal.subtract(4,2);
assertEquals(2, cal.getResult());
}
@Ignore
public voidtestMultiply(){
fail("Not yetimplemented");
}
@Test(timeout=2000)
public voidtestDivide(){
for(;;);
}
@Test(expected=ArithmeticException.class)
public voidtestDivideByZero(){
cal.divide(4,0);
}
}
执行该类,结果如下:其中testDivide执行失败,testMultiply未执行
BeforeClass
Before
After
Before
After
Before
After
Before
After
AfterClass
4.执行JUnit4 Test Suite
a.创建第二个测试类CalculatorTest2如下代码:
public classCalculatorTest2 {
@Test
public void test() {
System.out.println("TestCalculator2的测试方法被调用");
}
}
b.选择工程右键->new->other->选择"JUnit"下的“JUnit Test Suite”选项->单击next弹出框中选中package包,对CalculatorTest和CalculatorTest2两个类打上勾,finish->执行刚刚生成的名为AllTests的suite测试类,可同时执行package包里面打上勾的两个类
@RunWith(Suite.class)
@SuiteClasses({CalculatorTest.class, CalculatorTest2.class })
public class AllTests{
}
测试结果:
BeforeClass
Before
After
Before
After
Before
After
Before
After
AfterClass
TestCalculator2的测试方法被调用