TestNG是Java中的一個測試框架,類似JUnit 和NUnit, 功能都差不多,只是功能更加強大,使用也更方便。
詳細使用說明請參考官方鏈接:https://testng.org/doc/index.html
IDEA自帶了Junit 和testng 測試框架。但默認並不包含在你的項目或者模塊中。
一、所需環境
1、JDK
2、Maven
3、intellij idea
二、創建工程
三、導入相關依賴包和插件
1)IDEA安裝TestNG
進入設置->Browse Repositories->搜索“testng”進行下載,下載完成后重啟IDEA。
若IDEA已經安裝TestNG的插件,顯示如下:
TestNG-J:idea 自己做的插件, 默認存在
2)導入testNG依賴包
在pom.xml中添加:
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>7.3.0</version>
<scope>test</scope>
</dependency>
3)添加編譯插件和執行測試插件:
在pom.xml中添加:
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
//<source>${jdk.target.version}</source>
//<target>${jdk.target.version}</target>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.15</version>
<configuration>
<!--<testFailureIgnore>true</testFailureIgnore>-->
<forkMode>never</forkMode>
<argLine>-Dfile.encoding=UTF-8</argLine>
<suiteXmlFiles>
<suiteXmlFile>xml/testNG.xml</suiteXmlFile>
</suiteXmlFiles>
</configuration>
</plugin>
</plugins>
</build>
四、創建測試類
1)在Java文件夾下創建
打開需要進行單元測試的方法,選擇類名,點擊Alt+Enter鍵(windows)/Option+Enter鍵(mac),選擇Create Test,右鍵菜單->go to->test(alt+command+t)
第一次創建單元測試方法,可能會提示“TestNG library not found In the module”,是因為沒有在pom.xml文件中,寫入TestNG插件的依賴,點擊下圖的“Fix”按鈕,即可自動添加:
setUp/@Before:創建@Before方法
tearDown/@After:創建@After方法
Show inherited methods:為父類的方法創建單元測試
2)規范單元測試的存放路徑:
Preferences --> Plugins 安裝Junit Generator V2.0
設置Junit的Output Path目錄為${SOURCEPATH}/../test/${PACKAGE}/${FILENAME},否則默認為${SOURCEPATH}/test/${PACKAGE}/${FILENAME},此目標和Maven設置test目錄不一致。
File->other settings-> default settings->junit generator:
去掉JUnit3和JUnit4Tab中生成Package中前面的test目錄
Junit自動生成測試類:
右鍵類->generate->
找到需要test的類,使用command+N快捷鍵,選中 Junit test 即會自動生成Test代碼
Run->Edit Configurations->Defaults->TestNG:
output directory:${SOURCEPATH}/../../test/java/${PACKAGE}/${FILENAME}
3)編寫testNG.xml
<?xml version="1.0" encoding="utf-8" ?>
<suite name="testproj" parallel="false">
<test name="testDemo1">
<classes>
<class name="TestDemo"></class>
</classes>
</test>
</suite>
五、運行testNG.xml
ps:類的圖標上有紅色箭頭表示已經是測試類了,把測試相關的東西刪了就可以用shift+ctrl+t創建測試類了,比如是否繼承了TestCase