0

This is the code I used to have to open its corresponding web driver by browser.

@BeforeClass
@Parameters("browser")
public void openDriver(String browser) throws Exception {
    driver = help.getRemoteDriver(help.GRID,browser);
.....

Just wondering is there any way to assign value to a variable in class? not in method? for example.

public class Test{
   WebDriver driver;

   @Parameters("browser")
   public String browser = //"{browser}"; 

   @Test
   void test1(){
      driver = help.getRemoteDriver(help.GRID,browser);
   }

}

So I can call this String browser variable without @Parameters in the next new test. Even its child class.

Thank you in advance.

deokyong song
  • 162
  • 12
  • You exactly did that in the first code snippet by getting `browser` in a `beforeClass` method. Only difference is that along with initializing `driver`, you can declare a `browser` field in the class and initialize it as well. – Gautham M Feb 04 '22 at 08:22

1 Answers1

1

For Parameters annotation METHOD, CONSTRUCTOR, TYPE target ElementTypes defined.

@Retention(RUNTIME)
@Target({METHOD, CONSTRUCTOR, TYPE})
public @interface Parameters {|
...

There is no FIELD in target, so it's not possible to set this annotation for the class field.

But you might also set it in constructor.

public class MyTest {

   WebDriver driver;

   public String browser;

   @Parameters({ "browser" })
   public MyTest(String browser) {
       this.browser = browser;
   }

   @Test
   void test1(){
      driver = help.getRemoteDriver(help.GRID,browser);
   }

}

testng.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="suite-name">
    <test name="test-name">
        <parameter name="browser" value="chrome"/>
        <classes>
            <class name="my.package.name.MyTest"/>
        </classes>
    </test>
</suite>

What do Java annotation ElementType constants mean?

Max Daroshchanka
  • 2,698
  • 2
  • 10
  • 14
  • Thank you for your comment. Probably I have to set a filed variable by the constructor and it would be more suitable. – deokyong song Feb 06 '22 at 23:01
  • Excuse me... How can I declare the MyTest then? to construct MyTest, I should pass the String.. – deokyong song Mar 18 '22 at 02:02
  • @deokyongsong as you see, you might define a parameter in testng.xml, so it will be passed to the constructor. `@Parameters` annotation aimed to inject parameters from xml, that's its the main goal by design. – Max Daroshchanka Mar 18 '22 at 08:39