一、idea 集成單元測試工具 junit
步驟:1通過idea 創建meaven 項目
2如何集成junit
有兩種方式,a通過在pom.xml 中配置junit
b 通過plugins 下載junit 和junitgenerator-v2 插件,一定要全部勾選上
操作就是選擇 ->file->setings->plugins 能看到下方頁面
在搜索框中輸入junit 就能找到對應插件了,勾選上點擊apply 重啟下idea 就能安裝好
接下來就是配置好junitgenerator-v2 ,在setings 的other settings 中
在junit Generator 中將output path 修改為 :${SOURCEPATH}/../../test/java/${PACKAGE}/${FILENAME} (主要為了生成的Junit case 不和主程序文件在同一個目錄)
template 選擇junit4
如何快捷生成單元測試模板
a、選擇需要被測的類 , 快捷鍵 alt +insert 可以看到對應彈窗
點擊junit test 就可以了
b、 選擇需要被測的類,點擊右鍵,
選擇goto ,選擇test ,點擊create new test 會彈窗
勾選上需要測試方法,會自動生成對應用例模板
生成用例的模板
這樣只需要在生成的用例模板中填充好數據和斷言就行了
4idea 集成jacoco ,如果meavn 項目直接在pom.xml 中配置
<dependency>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.4</version>
</dependency>
生成對應報告需要配置對應模板
<build>
<plugins>
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.8.4</version>
<configuration>
<destFile>target/coverage-reports/jacoco-unit.exec</destFile>
<dataFile>target/coverage-reports/jacoco-unit.exec</dataFile>
</configuration>
<executions>
<execution>
<id>jacoco-initialize</id>
<goals>
<goal>prepare-agent</goal>
</goals>
</execution>
<!--這個report:對代碼進行檢測,然后生成index.html在 target/site/index.html中可以查看檢測的詳細結果-->
<execution>
<id>jacoco-site</id>
<phase>package</phase>
<!--<phase>test</phase>寫上test的時候會自動出現site文件夾,而不需執行下面的jacoco:report步驟,推薦-->
<goals>
<goal>report</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
配置完之后,如果點擊meavn 下的test 就可以看到site 目錄下有對應的報告文件
2直接在idea中安裝jacoco 插件
選擇單元測試文件,點擊
可以在meavn中看到數據
點擊導出報告,則可以在瀏覽器中看到對應的報告
里面可以具體看到覆蓋的代碼和方法以及沒有覆蓋的代碼
這樣就算是入門單元測試和代碼覆蓋了