標(biāo)簽形式實(shí)現(xiàn)用例失敗重試
前面的文章講解了可以通過(guò)標(biāo)簽的形式實(shí)現(xiàn)用例失敗重試的方法,@Test(retryAnalyzer = MyRetry.class)。
詳情可以參考文章:詳解TestNG中的用例失敗重試和自定義監(jiān)聽(tīng)器
但是通過(guò)@Test標(biāo)簽方式仍然存在一定的問(wèn)題,即該方法只能左右在類(lèi)或者方法上,當(dāng)測(cè)試類(lèi)非常多的時(shí)候,需要在每一個(gè)類(lèi)前都增加標(biāo)簽@Test(retryAnalyzer = MyRetry.class)。
有沒(méi)有什么全局的方式來(lái)搞定這件事兒呢?我們可以通過(guò)自定義listener來(lái)解決!
自定義Listener形式實(shí)現(xiàn)用例失敗重試
我們已經(jīng)通過(guò)標(biāo)簽實(shí)現(xiàn)了用例失敗的重試機(jī)制,那么我們就可以寫(xiě)一個(gè)listenser來(lái)控制標(biāo)簽。TestNG中提供了IAnnotationTransformer來(lái)讓我們實(shí)現(xiàn)這一目的。話(huà)不多說(shuō),直接上代碼
重試代碼邏輯的代碼實(shí)現(xiàn)如下:
- import org.testng.IRetryAnalyzer;
- import org.testng.ITestResult;
- public class MyRetry implements IRetryAnalyzer{
- private int retryCount = 0;
- private static final int maxRetryCount = 3;//用例失敗重新執(zhí)行3次
- @Override
- public boolean retry(ITestResult result) {
- if (retryCount < maxRetryCount) {
- retryCount++;
- return true;
- }
- return false;
- }
- }
自定義Retry 的listener代碼實(shí)現(xiàn)如下:
- import java.lang.reflect.Constructor;
- import java.lang.reflect.Method;
- import org.testng.IAnnotationTransformer;
- import org.testng.annotations.ITestAnnotation;
- public class RetryListener implements IAnnotationTransformer {
- @Override
- public void transform(ITestAnnotation testannotation, Class testClass,
- Constructor testConstructor, Method testMethod) {
- testannotation.setRetryAnalyzer(MyRetry.class);
- }
- }
測(cè)試類(lèi)代碼如下:
- import org.testng.annotations.Test;
- import static org.testng.Assert.assertEquals;
- public class Case1 {
- @Test
- public void f1() {
- System.out.println("f11");
- assertEquals("a","b");
- }
- @Test
- public void f2() {
- System.out.println("f21");
- assertEquals("a","a");
- }
- }
設(shè)置testng的配置文件,添加自定義的RetryListener
運(yùn)行結(jié)果如下,可以看到重試了3次。
備注:如果在一個(gè)case中,方法中有標(biāo)簽重試機(jī)制代碼如下(設(shè)置重試為1),那該如何處理呢?
- @Test(retryAnalyzer = MyRetry2.class)
- public void f1() {
- System.out.println("f11");
- assertEquals("a","b");
- }
我們運(yùn)行代碼會(huì)發(fā)現(xiàn)以testng的配置文件中的添加自定義RetryListener中使用的MyRetry.class為主。
原文地址:https://www.toutiao.com/i6954273928218984999/