Get Name of test in a custom keyword

Hello,

I would like to get the name of the current test case as I would like to use that as part of a new user’s username. I want to wrap up creating a new user through the site in a single keyword.

I can from another post (In the groovy script, how may we know the current test case id? - Katalon Studio - Katalon Community) an example of how to get the test id from the testContext in a TestListener, but is it possible to get this through a keyword?

I am new to groovy, am I right in thinking TestCaseContext is abstract and can’t be instantiated in a custom keyword? Is there a concrete type I can use?

Wayne,

but is it possible to get this through a keyword?

Why do you want a keyword which returns the name of the current test case?

I think it would be enough if you create a GlobalVariable.currentTestCaseName with String type.

And in you TestLister, you want this:

@BeforeTestCase
def sampleBeforeTestCase(TestCaseContext testCaseContext) {
    GlobalVariable.currentTestCaseId = testCaseContext.getTestCaseId()
}

Then you can refer to the global variable in your test cases:

WebUI.comment(">>> GlobalVariable.currentTestCaseId is ${GlobalVariable.currentTestCaseId}")
3 Likes

Thanks, I’ve always tried to avoid global variables in general but this does exactly what I need.

Hi,

This works perfectly for a parent test case. testCaseContext.getTestCaseId(), gives the name of the test case fine.

But in scenario where there’s a parent Test case, which calls sub testcases, using callTestCase, from within the listener, it always gives the parent test case id.
It should ideally give the name of the called sub-test case.
Not sure, if the listener gets called for a test case that is called from another test case.

Thanks,
Brijesh

I have made another post in the “tips and tricks” category. I showed a running code where sub testcases can print the TestCaseId of themselves:

2 Likes

Thank you @kazurayam, The solution works perfectly fine !

Wish the Test Listener methods could get triggered for called test cases too…

what about this? Pass in the scripts class which is it’s name and do a search in the scripts folder for the file then return the folder name which is the test case name.

/**
 * pass in script's class such as this.getClass() to return test case name by getting parent folder name
 * @param scriptClass = this.getClass()
 * @ return String
 */
@Keyword
String getTestCaseName(java.lang.Class scriptClass = this.getClass()) {

  String groovyFile = scriptClass.toString().replace('class ','') + '.groovy'

  def directory = new File('Scripts')

  def filePattern = ~/${groovyFile}/

  if (!directory.isDirectory())
 {
   System.exit(-2)
  }

 String testCaseName = null

  def findFileNameClosure = 
  {
    if (filePattern.matcher(it.name).find())
    {
      testCaseName = it.getParentFile().getName().toString()
    }
  }

  directory.eachFileRecurse(findFileNameClosure)

  return testCaseName

}

1 Like