Junit单元测试框架
功能
可以用来对方法进行测试,它是第三方公司开源出来的(很多开发工具已经集成了Junit框架,比如IDEA)
优点
- 可以灵活的编写测试代码,可以针对某个方法执行测试,也支持一键完成对全部方法的自动化测试,且各自独立。
- 不需要程序员去分析测试的结果,会自动生成测试报告出来
具体步骤
1、为需要测试的业务类,定义对应的测试类,并为每个业务方法,编写对应的测试方法(必须:公共、无参、无返回值)
2、为需要测试的业务类,定义对应的测试类,并为每个业务方法,编写对应的测试方法(必须:公共、无参、无返回值)
3、测试方法上必须声明@Test注解,然后在测试方法中,编写代码调用被测试的业务方法进行测试;
4、开始测试:选中测试方法,右键选择“JUnit运行”,如果测试通过则是绿色;如果测试失败,则是红色。
实操
断言机制
断言机制,程序员可以通过预测业务方法的结果
下面示例中如果fund.maxReturn的结果不为880,则显示异常,异常提示信息为 computeMaxResult compute error.
@Test
public void test_computeMaxResult() {
Fund fund = new Fund();
fund.upGrid = true;
fund.startPrice = 0.361f;
fund.gridSize = 0.004f;
fund.gridTotalNum = 40000;
fund.gridTradeNum = 4000;
fund.currentPrice = 0.366f;
FoundComputeCore.computeFundGridNum(fund);
FoundComputeCore.computeMaxResult(fund);
System.out.println(fund.maxReturn);
// 断言机制,程序员可以通过预测业务方法的结果
Assert.assertEquals("computeMaxResult compute error.", 880,fund.maxReturn);
}
常用注解
测试代码
public class FoundComputeCoreTest {
@Before
public void test1(){
System.out.println("test1 执行了");
}
@After
public void test2(){
System.out.println("test2 执行了");
}
@BeforeClass
public static void test3(){
System.out.println("test3 执行了");
}
@AfterClass
public static void test4(){
System.out.println("test4 执行了");
}
@Test
public void test_computeFundGridNum() {
Fund fund = new Fund();
fund.gridTotalNum = 1000;
fund.gridTradeNum = 100;
FoundComputeCore.computeFundGridNum(fund);
FoundComputeCore.computeFundGridNum(null);
}
@Test
public void test_computeMaxResult() {
Fund fund = new Fund();
fund.upGrid = true;
fund.startPrice = 0.361f;
fund.gridSize = 0.004f;
fund.gridTotalNum = 40000;
fund.gridTradeNum = 4000;
fund.currentPrice = 0.366f;
FoundComputeCore.computeFundGridNum(fund);
FoundComputeCore.computeMaxResult(fund);
// 断言机制,程序员可以通过预测业务方法的结果
Assert.assertEquals("computeMaxResult compute error.", 880, fund.maxReturn);
}
}
输出
test3 执行了
test1 执行了
test2 执行了
test1 执行了
test2 执行了
test4 执行了