主要内容
编写测试报告,写出用Eclipse和JUnit开发单元测试的一般步骤、测试代码以及测试结果的屏幕截图。
步骤
在Eclipse中创建一个新的Java项目
public class Calculator {
public int evaluate(String expression) {
int sum = 0;
for (String summand: expression.split("\\ +"))
sum += Integer.valueOf(summand);
return sum;
}
}
右击Calculator.java项目,再单击弹出的快捷菜单中New→JUnit Test Case菜单项。进入如图界面:
单击Finish按钮并单击OK按钮
Eclipse生成的CalculatorTest.java文件如下
import static org.junit.jupiter.api.Assertions.*;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.jupiter.api.Test;
class CalculatorTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void setUpAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
final void test() {
fail("Not yet implemented"); // TODO
}
}
修改CalculatorTest文件如下
import static org.junit.jupiter.api.Assertions.*;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.jupiter.api.Test;
class CalculatorTest {
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void setUpAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
final void test() {
Calculator calculator = new Calculator();
int sum = calculator.evaluate("1+2+3");
assertEquals(6,sum);
}
}
右击Test4,在菜单中单击Build Path →Configure Build Path菜单项,进入如图所示界面
可以看出,该项目已添加JUnit5库文件
右击CalculatorTest .java文件,在弹出框中单击Run As →JUnit Test菜单项,执行JUnit测试用例,进入如图界面