Aks..
Aks..

Reputation: 1383

Why cannot System.setProperty be used at Class level?

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"

Upvotes: 0

Views: 4304

Answers (3)

Suresh Bhandari
Suresh Bhandari

Reputation: 109

a basic class need method to perform any action

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

Upvotes: 0

dimo414
dimo414

Reputation: 48824

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.

Upvotes: -1

user207421
user207421

Reputation: 310913

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.

Upvotes: 5

Related Questions