junit框架:
junit是开源的java单元测试框架。
今天我们来介绍一下junit5,junit5由三个不同的子项目模块组成,包括junit platform、junit jupiter和junit vintage。它支持java8以及以上版本,编辑器我在这使用的是intellij idea,只需要查看最后结果,就知道整个项目的方法接口是否通畅。每个单元测试用例相对独立,由junit 启动,自动调用。不需要添加额外的调用语句。
添加,删除,屏蔽测试方法,不影响其他的测试方法。
junit主要是用于做白盒测试,白盒测试操作步骤如下:
1、测试计划阶段:根据需求说明书,制定测试进度。
2、测试设计阶段:根据代码的功能,人工设计测试用例进行基本功能测试。依据程序设计说明书,按照一定规范化的方法进行软件结构划分和设计测试用例。
3、测试执行阶段:输入测试用例,得到测试结果。
4、测试总结阶段:对比测试的结果和代码的预期结果,分析错误原因,找到并解决错误。
接下来我们介绍一下里面的注解:
@test:表示测试方法,不用声明任何属性。
@parameterizedtest:表示方法是测试方法,此外该注释还可以让一个测试方法使用不同的人参与多次运行。
@repeatedtest:该注释可以让测试方法自定义重复运行次数。
@testfactory:表示一个方法是基于数据驱动的动态测试数据源。
@displayname:声明测试类或测试方法的自定义显示名称。
@beforeeach:表示在每一个测试方法运行前,都运行该指定方法。
@aftereach:表示在每一个测试方法运行后,都运行该指定方法。
@beforeall:在当前类的所有测试方法之前执行,此方法可以包含一些初始化代码。
@afterall:在当前类的所有测试方法之后执行。
@disabled:注明一个测试类或方法无效。
断言:
fail:断言测试失败。
asserttrue/asserfalse:断言真或假。
assertnull/assertnotnull:断言为空或不为空。
assertequals/assertnotequals:断言两个值相不相等。
assertarrayequals:断言数组元素全部相同。
assertsame/assertnotsame:断言两个对像是否相同。
assertthrows/assertdoesnotthrow:断言是否抛出异常。
assertall:断言多个条件均满足;
下面我们创建一个类,创建几个方法:
package test;//包机制import java.lang.reflect.array;public class mixedoperation { public int mixeoperation(int x,int y){ return division((x+y),y); } public int division(int x,int y){ int result=(x/y); return result; } public static void main(string[] args) { mixedoperation mixedoperation=new mixedoperation(); system.out.println(mixedoperation.mixeoperation(5,1)); }}
我们创建了一个名为mixedoperation的类;
package test;import org.junit.jupiter.api.*;import org.junit.jupiter.params.parameterizedtest;import org.junit.jupiter.params.provider.csvsource;public class mixedoperationtest { private mixedoperation mixedoperation; @beforeeach public void init(){ mixedoperation=new mixedoperation(); } @test public void successtest(){ system.out.println("run a test:x=4,y=2"); int result=mixedoperation.mixeoperation(4,2); assertions.assertequals(3,result); } /* @displayname("失败") public void errortest(){` system.out.println("run a test:x=4,y=0"); arithmeticexception exception=new arithmeticexception( arithmeticexception.class -> { mixedoperation.mixeoperation(4, 0); } ); }*/ @disabled("参数") @test @displayname("参数") @parameterizedtest @csvsource({"6,3,3","5,2,3","6,2,4"}) public void catest(int x,int y,int excepted){ system.out.println("run a test :x="+x+"y="+y); system.out.println(excepted); int t= mixedoperation.mixeoperation(x,y); assertions.assertequals(excepted,t); } @disabled @test public void next(){ system.out.println("抛出一个异常"); system.out.println(assertions.assertthrows(illegalargumentexception.class, () ->mixedoperation.mixeoperation(2,0))); } @disabled @test void error(){ assertions.assertthrows(exception.class,()->{assertions.assertequals(1,0);}); } @test void sure(){ int result=mixedoperation.mixeoperation(4,2); assertions.asserttrue(3==result);//断言相等 }}
这是我们创建一个名为mixedoperationtest的测试类;
相关推荐:《java视频教程》
以上就是白盒测试框架(junit)的使用的详细内容。