当前 TestNG 中的 InvocationCount

6

我有一个需要使用TestNG测试的方法,并使用以下注释进行标记:

@Test(invocationCount=10, threadPoolSize=5)

现在,在我的测试方法中,我希望能够获取当前正在执行的调用计数。这是否可能?如果是,那么我很高兴知道如何做。

更合适的示例:

@Test(invocationCount=10, threadPoolSize=5)
public void testMe() {
   System.out.println("Executing count: "+INVOCATIONCOUNT); //INVOCATIONCOUNT is what I am looking for
}

为了参考,我在Eclipse中使用TestNG插件。

6个回答

9
您可以通过在测试方法中添加ITestContext参数来使用TestNG依赖注入功能。请参阅http://testng.org/doc/documentation-main.html#native-dependency-injection
从ITestContext参数中,您可以调用其getAllTestMethods()方法,该方法返回一个ITestNGMethod数组。它应该只返回一个元素的数组,该元素指向当前/实际测试方法。最后,您可以调用ITestNGMethod的getCurrentInvocationCount()方法。
您的测试代码应该类似于以下示例:
@Test(invocationCount=10, threadPoolSize=5)
public void testMe(ITestContext testContext) {
   int currentCount = testContext.getAllTestMethods()[0].getCurrentInvocationCount();
   System.out.println("Executing count: " + currentCount);
}

2
您可以使用类似这样的内容:

您可以使用以下内容:

public class getCurrentInvocationCount {

  AtomicInteger i = new AtomicInteger(0);

  @Test(invocationCount = 10, threadPoolSize=5)
  public void testMe()  {
   int count= i.addAndGet(1);
   System.out.println("Current Invocation count "+count)

  }
}

2
您可以按照以下方式获取当前调用计数:
public class getCurrentInvocationCount {
int count;

 @BeforeClass
 public void initialize() {
     count = 0;
  }

 @Test(invocationCount = 10)
 public void testMe()  {
   count++;
   System.out.println("Current Invocation count "+count)

  }
 }

我知道这种方法有点愚蠢。但它可以达到你的目的。你可以参考testNG源代码中的类来获取实际的当前invocationCount


1
感谢你的努力,Vikram。然而,你上面提到的方法只有在单线程下运行测试时才有用。正如你在我的问题中所看到的,我已经使用threadPoolSize=5注释了测试方法,这使得上述方法在这种情况下无法使用。我尝试将其设置为staticvolatile,但那并没有起作用。 - Mubin
你看了我给你的实际类链接吗? - vkrams
我已经阅读了文档(尽管没有查看实际的源代码),但是没有找到检索当前调用计数的任何规定。 - Mubin

1
您可以通过调用 ITestNGMethodgetCurrentInvocationCount() 方法来获得。

Pete,请问您能详细说明一下如何使用ITestNGMethod.getCurrentInvocationCount()吗?文档中没有提到。 - Immanuel

0

尝试在@Test方法中放置2个参数:

  1. java.lang.reflect.Method

    使用.getName()获取当前方法名称。

  2. ITestContext

    使用.getAllTestMethods()获取所有测试方法。然后使用forEach通过ITestNGMethod提取它们并与第1点中的.getName()进行比较。

最后,使用.getCurrentInvocationCount()来实现此目的。

@Test(invocationCount=10)
public void testMe(ITestContext context, Method method) {
    int invCountNumber = 0;
    for(ITestNGMethod iTestMethod: context.getAllTestMethods()) {
        if(iTestMethod.getMethodName().equals(method.getName())){
            invCountNumber = iTestMethod.getCurrentInvocationCount();
            break;
        }
    }
    System.out.println(invCountNumber);
}

以下是导入:

import java.lang.reflect.Method;
import org.testng.ITestContext;
import org.testng.ITestNGMethod;

-1

当您使用invocationCount时,测试会像for循环一样运行。 我发现这是获取测试执行计数的最简单方法。

int count;
@Test(invocationCount = 3)
 public void yourTest()  {
   count++;
   System.out.println("test executed count is: " + count)

  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接