0

I had tried using System.setProperty in main method with no issues, but when I switched to TestNG as part of my Selenium learning, I realized we cannot write System.setProperty at Class level. It should be either at method level or be in a static block. I just want to understand what is the feature of Java that is compelling us to do this.

public class NewTest {
    public String baseUrl = "http://newtours.demoaut.com/";
    static {
        System.setProperty("webdriver.chrome.driver","D:\\paths\\chromedriver.exe");    
    }

    WebDriver driver = new ChromeDriver();

    @Test
     public void f1() {
      ...}
   }

Writing this outside of static block shows compilation error like "Multiple markers at this line, Syntax error"

Aks..
  • 1,343
  • 1
  • 20
  • 42
  • If it's not in a `static` block, then when do you want it to execute? The compiler is asking you to use the proper syntax to specify when the code should run. – 4castle Nov 17 '16 at 06:15
  • According to Java syntax a "Statement" can only appear in a method or a static block. At class level you can only write declarations. It does not make sense otherwise, when would the statement be executed when you write it at class level? – Henry Nov 17 '16 at 06:15
  • Could you clarify what, exactly, is your goal? It's likely there's a reasonable way to do it with standard Java syntax. – dimo414 Nov 17 '16 at 06:57

3 Answers3

5

I just want to understand what is the feature of Java that is compelling us to do this.

The 'feature of Java' is that you can only write methods and declarations at class level, and System.setProperty() is neither: it is a method call.

user207421
  • 305,947
  • 44
  • 307
  • 483
0

a basic class need method to perform any action

note - same way you can't call System.out.println("");

Suresh Bhandari
  • 109
  • 1
  • 3
-1

Calling System.setProperty() in a static block is occurring at the class level. What is perhaps surprising you is that this only happens once per program - the first time your NewTest class is referenced. static fields and blocks are guaranteed to be executed exactly once per JVM invocation, and that's a feature. If you want your code to be run more often than that you don't want to use static statements.

JUnit and similar testing frameworks provided dedicated mechanisms for running setup code before each class or method that's invoked. See @Before and @BeforeClass, along with this question for more specifics about how to implement this behavior in JUnit.

If @Before/@BeforeClass don't address your question please edit it with more context to clarify what you're trying to accomplish. Including code samples of what you've tried - and why it hasn't worked - is particularly helpful.

Community
  • 1
  • 1
dimo414
  • 47,227
  • 18
  • 148
  • 244