ChrisG29
ChrisG29

Reputation: 1571

Is it possible to write the name of a testng test from a called method?

I'm running Selenium tests using Java (TestNG and IntelliJ) and am currently working on my reporting framework. My test setup looks something like this:

@Test
public void testLogin(){
  myKeyword.login();
}

myKeyword is a class of keywords that I have created, with a method called login. The login keyword will look like:

public void login(){
  myPage.typeInTextBox("Username");
  myPage.typeInTextBox("Password");
  myPage.buttonClick("Login");
}

My validation is built into the methods "buttonClick" and "typeInTextBox". They will look something like:

try{
  driver.findelement(By.id("myButton")).click();
}
catch (Exception e){
  Assert.fail("Could not click on the button.");
}

What I want to know is, is it possible for the "buttonClick" method to know the name of the test that's calling it?

I want to replace the "Assert.fail..." with my own function that will create a text file that I will use to log the information I want, which will need to include the name of the test that failed (in this case "testLogin).

Upvotes: 4

Views: 96

Answers (1)

PeterG
PeterG

Reputation: 506

One option would be to set the name of the current test somewhere, possibly to a static variable. How to do that for TestNG was described here.

public class Test { 
    @BeforeMethod
    public void handleTestMethodName(java.lang.reflect.Method method) {
        GlobalVariables.currentTestName = method.getName(); 
    }
...
}

Upvotes: 3

Related Questions