java之 junit單元測試案例【經典版】

一? junit單元測試

1.1 單元測試作用

單元測試要滿足AIR原則,即

A: automatic 自動化;

I: Independent? 獨立性;

R:Repeatable 可重復;

2.單元測試必須使用assert來驗證

1.2 案例1 常規單元測試

1.代碼

public class CalcDemo
{public int add(int x ,int y){return x + y;//return x * y;}public int sub(int x ,int y){return x - y;}
}

2.測試

public class AppTest {@Testvoid sub(){CalcDemo calcDemo = new CalcDemo();int retValue = calcDemo.sub(2, 2);assertEquals(0,retValue);System.out.println("");}
}

1.3?案例2?單元覆蓋率Coverage*

1.代碼

public class ScoreDemo
{public String scoreLevel(int score){if(score <= 0) {throw new IllegalArgumentException("缺考");} else if (score < 60) {return "弱";} else if (score < 70) {return "差";} else if (score <= 80) {return "中";} else if (score < 90) {return "良";} else {return "優";}}
}

2.測試

class ScoreDemoTest
{@Testvoid scoreLevel(){ScoreDemo scoreDemo = new ScoreDemo();assertEquals("弱",scoreDemo.scoreLevel(52));}@Testvoid scoreLevelv2(){ScoreDemo scoreDemo = new ScoreDemo();assertEquals("差",scoreDemo.scoreLevel(62));}@Testvoid scoreLevelv3(){ScoreDemo scoreDemo = new ScoreDemo();assertEquals("中",scoreDemo.scoreLevel(80));}@Testvoid scoreLevelv4(){ScoreDemo scoreDemo = new ScoreDemo();assertThrows(IllegalArgumentException.class,() -> scoreDemo.scoreLevel(-7));}
}

查看測試報告:對應覆蓋率

1.4?案例3?BeforeEach,BeforeAfterall

1.代碼

public class CalcDemo
{public int add(int x ,int y){return x + y;//return x * y;}public int sub(int x ,int y){return x - y;}
}

2.測試?

class CalcDemoTestV2
{CalcDemo calcDemo = null;static StringBuffer stringBuffer = null;@BeforeAllstatic void m1(){stringBuffer = new StringBuffer("abc");System.out.println("===============: "+stringBuffer.length());}@AfterAllstatic void m2(){System.out.println("===============: "+stringBuffer.append(" ,end").toString());}@BeforeEachvoid setUp(){System.out.println("----come in BeforeEach");calcDemo = new CalcDemo();}@AfterEachvoid tearDown(){System.out.println("----come in AfterEach");calcDemo = null;}@Testvoid add(){assertEquals(5,calcDemo.add(1,4));assertEquals(5,calcDemo.add(2,3));}@Testvoid sub(){assertEquals(5,calcDemo.sub(10,5));}
}

3.結果

1.5?案例4? junit+反射+注解實現測試

1.定義注解

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface AtguiguTest
{
}

2.定義調用類

public class CalcHelpDemo
{public int mul(int x ,int y){return x * y;}@AtguiguTestpublic int div(int x ,int y){return x / y;}@AtguiguTestpublic void thank(int x ,int y){System.out.println("3ks,help me test bug");}
}

3.定義測試類

@Slf4j
public class AutoTestClient
{public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException{//家庭作業,抽取一個方法,(class,p....)CalcHelpDemo calcHelpDemo = new CalcHelpDemo();int para1 = 10;int para2 = 0;Method[] methods = calcHelpDemo.getClass().getMethods();AtomicInteger bugCount = new AtomicInteger();// 要寫入的文件路徑(如果文件不存在,會創建該文件)String filePath = "BugReport"+ (DateUtil.format(new Date(), "yyyyMMddHHmmss"))+".txt";for (int i = 0; i < methods.length; i++){if (methods[i].isAnnotationPresent(AtguiguTest.class)){try{methods[i].invoke(calcHelpDemo,para1,para2);//放行} catch (Exception e) {bugCount.getAndIncrement();log.info("異常名稱:{},異常原因:{}",e.getCause().getClass().getSimpleName(),e.getCause().getMessage());FileUtil.writeString(methods[i].getName()+"\t"+"出現了異常"+"\n", filePath, "UTF-8");FileUtil.appendString("異常名稱:"+e.getCause().getClass().getSimpleName()+"\n", filePath, "UTF-8");FileUtil.appendString("異常原因:"+e.getCause().getMessage()+"\n", filePath, "UTF-8");}finally {FileUtil.appendString("異常數:"+bugCount.get()+"\n", filePath, "UTF-8");}}}}
}

4.查看結果

1.6?案例5? web工程單元測試

1.pom配置

   <!--test--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--test--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency>

2.處理類

@Service
public class MemberService
{public String add(Integer uid){System.out.println("---come in addUser,your uid is: "+uid);if (uid == -1){throw new IllegalArgumentException("parameter is negative。。。。");}return "ok";}public int del(Integer uid){System.out.println("---come in del,your uid is: "+uid);return uid;}
}

3.啟動類

@SpringBootApplication
public class App 
{public static void main( String[] args ){SpringApplication.run(App.class, args);System.out.println( "Hello World!" );}
}

4.測試類

@SpringBootTest
public class MemberTest {@Resource //真實調用,落盤mysql-MQ=redis。。。。測試條件充分的情況下private MemberService memberService1;//    @Test
//    void m1()
//    {
//        String result = memberService1.add(2);
//        assertEquals("ok",result);
//
//        System.out.println("----m1 over");
//    }@MockBeanprivate MemberService memberService2;//    @Test
//    void m2_NotMockRule()
//    {
//        String result = memberService2.add(2);
//        assertEquals("ok",result);
//
//        System.out.println("----m2_NotMockRule over");
//    }//    @Test
//    void m2_WithMockRule()
//    {
//        when(memberService2.add(3)).thenReturn("ok");//不真的進入數據庫/MQ,不落盤,改變return
//
//        String result = memberService2.add(3);
//        assertEquals("ok",result);
//
//        System.out.println("----m2_WithMockRule over");
//    }
@SpyBean //有規則按照規則走,沒有規則走真實
private MemberService memberService3;@Testvoid m3(){when(memberService3.add(2)).thenReturn("ok");String result = memberService3.add(2);System.out.println("----add result:  "+result);Assertions.assertEquals("ok",result);int result2 = memberService3.del(3);System.out.println("----del result2:  "+result2);Assertions.assertEquals(3,result2);//跨部門調用,不是寫代碼,累的是心,協調工作。    zzyybs@126.comSystem.out.println("----over");}
}

4.結果

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/web/46285.shtml
繁體地址,請注明出處:http://hk.pswp.cn/web/46285.shtml
英文地址,請注明出處:http://en.pswp.cn/web/46285.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

PSINS工具箱函數介紹——r2d

介紹工具箱里面r2d這個小函數的作用。 程序源碼 function deg r2d(rad) % Convert angle unit from radian to degree % % Prototype: deg r2d(rad) % Input: rad - angle in radian(s) % Output: deg - angle in degree(s) % % See also r2dm, r2dms, d2r, dm2r, dms2r% …

設計模式使用場景實現示例及優缺點(行為型模式——觀察者模式)

阿爾法的身體內部有一個智能芯片&#xff0c;這個芯片能夠根據環境和需求自動改變它的行為模式。當阿爾法需要完成不同任務時&#xff0c;它的內部狀態會發生變化&#xff0c;進而改變它的行為&#xff0c;就像是它變成了另一個機器人一樣。 一天&#xff0c;智能城的市長接到一…

多種方式實現 元素高度絲滑的從0-1顯示出來

選擇合適的方式&#xff0c;給用戶更好的體驗&#xff0c;多種方式實現 元素高度絲滑的從0-1顯示出來。 能用 CSS 實現的動畫&#xff0c;就不要采用 JS 去實現。 1、瀏覽器可以對CSS動畫進行優化&#xff0c;其優化原理類似于requestAnimationFrame&#xff0c;會把每一幀的…

java基礎學習:序列化之 - Fast serialization

在Java中&#xff0c;序列化是將對象的狀態轉換為字節流的過程&#xff0c;以便保存到文件、數據庫或通過網絡傳輸。Java標準庫提供了java.io.Serializable接口和相應的機制來進行序列化和反序列化。然而&#xff0c;標準的Java序列化機制性能較低&#xff0c;并且生成的字節流…

appium2.0 執行腳本遇到的問題

遇到的問題&#xff1a; appium 上的日志信息&#xff1a; 配置信息 方法一 之前用1.0的時候 地址默認加的 /wd/hub 在appium2.0上&#xff0c; 服務器默認路徑是 / 如果要用/wd/hub 需要通過啟動服務時設置基本路徑 appium --base-path/wd/hub 這樣就能正常執行了 方法二…

關于Kafka的17個問題

1.Kafka 的設計時什么樣的呢&#xff1f; Kafka 將消息以 topic 為單位進行歸納 將向 Kafka topic 發布消息的程序成為 producers. 將預訂 topics 并消費消息的程序成為 consumer. Kafka 以集群的方式運行&#xff0c;可以由一個或多個服務組成&#xff0c;每個服務叫做一個…

前端css常用筆記

文章目錄 一、樣式二、vue筆記2.1、組件之間的通信2.1.1 子組件調用父組件的方法2.1.2 父組件調用子組件的方法2.1.3 孫組件調用祖父組件方法的實現 2.2、使用若依時,node_nodules越來越大的問題2.3、echart筆記 一、樣式 1 文字與圖標對不齊的解決方法 /**給icon加上這個樣式即…

mysql的索引事務和存儲引擎

一、索引 1、索引 索引的概念 &#xff1a;索引是一個排序的列表&#xff0c;在列表當中存儲索引的值以及索引值對應數據所在的物理行。 索引的引用&#xff1a; 使用索引之后&#xff0c;就不需要掃描全表來定位某行的數據。 加快數據庫的查詢速度。 索引可以是表中的一…

ubuntu 網絡 通訊學習筆記2

1.ubuntu 網絡常用命令 在Ubuntu中&#xff0c;有許多網絡相關的常用命令。以下是一些主要命令及其用途&#xff1a; ifconfig&#xff1a;此命令用于顯示和配置網絡接口信息。你可以使用它來查看IP地址、子網掩碼、廣播地址等。 例如&#xff1a;ifconfig 注意&#xff1a…

在 K8s 上使用 KubeBlocks 提供的 MySQL operator 部署高可用 WordPress 站點

引言 WordPress WordPress 是全球最流行的內容管理系統&#xff08;CMS&#xff09;&#xff0c;自 2003 年發布以來&#xff0c;已成為網站建設的首選工具。其廣泛的插件和主題生態系統使用戶能夠輕松擴展功能和美化外觀。活躍的社區提供豐富的資源和支持&#xff0c;進一步…

[RK3588-Android12] 關于如何取消usb-typec的pd充電功能

問題描述 RK3588取消usb-typec的pd充電功能 解決方案&#xff1a; 在dts中fusb302節點下usb_con: connector子節點下添加如下熟悉&#xff1a; 打上如下2個補丁 diff --git a/drivers/usb/typec/tcpm/tcpm.c b/drivers/usb/typec/tcpm/tcpm.c index c8a4e57c9f9b..173f8cb7…

使用OpenCV尋找圖像中的輪廓

引言 OpenCV&#xff08;Open Source Computer Vision Library&#xff09;是一個開源的計算機視覺和機器學習軟件庫。它提供了大量的視覺處理功能&#xff0c;包括圖像和視頻捕獲、特征檢測與匹配、圖像變換、圖像分割、顏色空間轉換等。在圖像處理中&#xff0c;尋找圖像中的…

electron項目中實現視頻下載保存到本地

第一種方式&#xff1a;用戶自定義選擇下載地址位置 渲染進程 // 渲染進程// 引入 import { ipcRenderer } from "electron";// 列表行數據下載視頻操作&#xff0c;diffVideoUrl 是視頻請求地址 handleDownloadClick(row) {if (!row.diffVideoUrl) {this.$message…

【數字電路學習新助手】掌握電路仿真軟件,開啟數字電路知識的新篇章

在信息科技日新月異的今天&#xff0c;數字電路知識的重要性不言而喻。無論是通信工程、計算機科學與技術&#xff0c;還是電子信息技術等領域&#xff0c;數字電路都是基礎中的基礎。然而&#xff0c;對于初學者來說&#xff0c;數字電路的學習往往充滿了挑戰。幸運的是&#…

Axure中繼器入門:打造你的動態原型

前言 中繼器 是 Axure 中的一個高級功能&#xff0c;它能夠在靜態頁面上模擬后臺數據交互的操作&#xff0c;如增加、刪除、修改和查詢數據&#xff0c;盡管它不具備真實數據存儲能力。 中繼器就像是一個臨時的數據庫&#xff0c;為我們在設計原型時提供動態數據管理的體驗&a…

中職省培丨2024年大數據技術中職教師專業技能培訓班企業參觀實踐圓滿結束

7月17日&#xff0c;“2024年大數據技術中職教師專業技能培訓班&#xff08;省培&#xff09;”參訓老師蒞臨廣東泰迪智能科技股份有限公司產教融合實訓中心開展企業參觀實踐。泰迪智能科技董事長張良均、中職業務部總監李振林、中職業務部經理黃炳德、校企合作經理吳桂鋒及來自…

centos跳過首次創建用戶

centos跳過首次創建用戶 centos跳過首次創建用戶 在安裝系統后&#xff0c;登錄的時候總是讓新建一個普通用戶&#xff0c;很是煩人&#xff0c;于是想辦法解決一下 方法一 在CentOS上&#xff0c;圖形化登錄&#xff08;如GNOME&#xff09;通常要求您創建一個用戶來登錄。…

.net core appsettings.json 配置 http 無法訪問

1、在appsettings.json中配置"urls": "http://0.0.0.0:8188" 2、但是網頁無法打開 3、解決辦法&#xff0c;在Program.cs增加下列語句 app.UseAntiforgery();

vue 如何做一個動態的 BreadCrumb 組件,el-breadcrumb ElementUI

vue 如何做一個動態的 BreadCrumb 組件 el-breadcrumb ElementUI 一、ElementUI 中的 BreadCrumb 定義 elementUI 中的 Breadcrumb 組件是這樣定義的 <template><el-breadcrumb separator"/"><el-breadcrumb-item :to"{ path: / }">主…

爬蟲的概念

爬蟲&#xff08;Web Crawler 或 Web Spider&#xff09;是一種自動化腳本或程序&#xff0c;用于瀏覽萬維網&#xff08;World Wide Web&#xff09;并抓取網頁上的信息。它們按照設定的規則自動地訪問互聯網上的網頁&#xff0c;提取所需的數據&#xff0c;如文本、圖片、視頻…