目錄
(一)TestNG學習之路—HelloWorld入門
(二)TestNG學習之路—注解及屬性概覽
(三)TestNG學習之路—TestNG.xml/YAML
(四)TestNG學習之路—注解詳述之@Test
(五)TestNG學習之路—注解詳述之參數化
(六)TestNG學習之路—注解詳述之@Factory
(七)TestNG學習之路—注解詳述之忽略測試
(八)TestNG學習之路—注解詳述之并發(fā)
(九)TestNG學習之路—失敗測試重跑
(十)TestNG學習之路—編碼執(zhí)行TestNG
(十一)TestNG學習之路—BeanShell高級用法
(十二)TestNG學習之路—注解轉換器
(十三)TestNG學習之路—方法攔截器
(十四)TestNG學習之路—TestNG監(jiān)聽器
(十五)TestNG學習之路—依賴注入
(十六)TestNG學習之路—測試報告
(十七)基于TestNG+Rest Assured+Allure的接口自動化測試框架
前言
用過Jmeter的童鞋肯定都聽說過Beanshell,BeanShell是一種松散類型的腳本語言(和JS類似),一種完全符合java語法的java腳本語言,但其也擁有自己的語法和方法,足以可見其功能的強大。更讓你吃驚的是,TestNG居然可以同Beanshell結合,構建強大的testng.xml配置。
環(huán)境配置
登錄beanshell官網下載bsh-2.0b4.jar,放到$JAVA_HOME/jre/lib/ext目錄下。更詳細的說明可以參考beanshell手冊。
To install as an extension place the bsh.jar file in your
$JAVA_HOME/jre/lib/ext folder. (OSX users: place the bsh.jar in
/Library/Java/Extensions or ~/Library/Java/Extensions for individual users.)
Or add BeanShell to your classpath like this:
windows: set classpath %classpath%;bsh-xx.jar
示例
當在<script>標簽出現在testng.xml時,TestNG將忽略當前test標簽下的組和方法的<include>,<exclude>標簽,您的BeanShell表達式將是決定是否執(zhí)行測試方法的唯一因素。
編寫測試類如下:
import org.testng.Assert;
import org.testng.annotations.*;
@Test(groups = "test1")
public class TestNGHelloWorld1 {
@BeforeTest
public void bfTest() {
System.out.println("TestNGHelloWorld1 beforTest!");
}
@Test(expectedExceptions = ArithmeticException.class, expectedExceptionsMessageRegExp = ".*zero")
public void helloWorldTest1() {
System.out.println("TestNGHelloWorld1 Test1!");
int c = 1 / 0;
Assert.assertEquals("1", "1");
}
@Test()
@Parameters(value = "para")
public void helloWorldTest2(@Optional("Tom")String str) {
Assert.assertEquals("1", "1");
System.out.println("TestNGHelloWorld1 Test2! "+ str);
}
@AfterTest
public void AfTest() {
System.out.println("TestNGHelloWorld1 AfterTest!");
}
}
testng.xml如下:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="All Test Suite" group-by-instances="true">
<test verbose="2" preserve-order="true" name="Test">
<method-selectors>
<method-selector>
<script language="beanshell">
<![CDATA[
groups.containsKey("test1")
]]>
</script>
</method-selector>
</method-selectors>
<classes>
<class name="TestNGHelloWorld1"/>
</classes>
</test>
</suite>
執(zhí)行結果如下:
TestNGHelloWorld1 beforTest!
TestNGHelloWorld1 Test1!
TestNGHelloWorld1 Test2! Tom
TestNGHelloWorld1 AfterTest!
===============================================
All Test Suite
Total tests run: 2, Failures: 0, Skips: 0
===============================================
由此可見,beanshell可讓測試/開發(fā)人員更靈活地對testng.xml進行配置。但需要關注以下幾點:
- 它必須返回一個布爾值。除了這個約束之外,還允許任何有效的BeanShell代碼(例如,您可能想在工作日期間返回true,在周末返回false,這將允許您根據日期以不同的方式運行測試)。
- 為了方便起見,TestNG定義了以下變量:
java.lang.reflect.Method method: 當前的測試方法
org.testng.ITestNGMethod testngMethod: 當前測試方法的描述
java.util.Map<String, String> groups: 當前測試方法所屬組的映射
上述testng.xml的groups.containsKey返回的正是布爾值。
擴展學習資料
關于beanshell的學習,可參考beanshell手冊。