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.

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.

  • Thank you. I'll try this way. – junghan Mar 15 at 11:21
  • Yup, This is pure gold to me. Thank you! It is beautifully working – junghan Mar 22 at 2:44
  • 1
    No problem. I'm glad it's working for you. – Klynt Mar 22 at 13:04
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.

  • 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 at 8:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.