1

I'm trying to adapt testrail api. I want to set a integer testID value for a @Test and get the value at iTestListener.

In testNG, is there a way to specify a test id for each @Test?

I tried getTestName, but it seems that it's not designed to use this way.

junghan
  • 102
  • 7

2 Answers2

3

@Test annotation is the best way to achieve this and there are various guides online to do it.

Simply put you'd create a new annotation class

e.g.

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface TestParameters {
    String[] testRailId() default "";
}

Then within your test put the test / case ID (without the preceding T or C, as the testrail API doesn't accept them).

@Test(priority = 0, description = "Some description")
@TestParameters(testRailId= {"1234"})
public void My_Test(){
   //do something
   }

Then in the listener:

String[] testID;
IClass obj = iTestResult.getTestClass();
Class<?> newobj = obj.getRealClass();
Method testMethod = null;
testMethod = newobj.getMethod(iTestResult.getMethod().getMethodName());

if (testMethod.isAnnotationPresent(TestParameters.class)) {
   TestParameters useAsTestName = testMethod.getAnnotation(TestParameters.class);
   // Get the TestCase ID for Test Rail
   testID = (useAsTestName.testRailId());
   // Do something with the testID
   }

There are other ways to do it, but they usually start to fall over when you're using TestNG's parallel testing abilities.

Klynt
  • 544
  • 2
  • 9
0

Hmm.. I think I found a way. It looks a little bit wierd, but it works. add ITestContext parameter at the test method, and set a value at the context.

@Test()
public void sample(ITestContext context){
context.setAttribute("testId", 11111);
//Your test
assertEquals(true, true);
}

At the on success or fail method, get context from result.

@Override
public void onTestSuccess(ITestResult result){
ITestContext context = result.getTestContext();
System.out.prinln(context.getAttribute("testId")); // you can get the attribute!
}

Do some other things in the @Test method seems weird. But it works for now.

junghan
  • 102
  • 7
  • I think specifying a value at the parameter of @Test annotation is the best. But I don't know how to do it. – junghan Feb 12 '19 at 08:58