Testing / Selenium Interview questions
What is the difference between @BeforeMethod and @BeforeClass in TestNG?
Both are TestNG setup annotations, but they run at different scopes within a test class.
| @BeforeMethod | @BeforeClass |
| Runs before every single @Test method | Runs once before any @Test method in the class |
| Good for launching a fresh browser per test | Good for one-time setup shared across all tests in the class |
A typical pattern uses @BeforeClass for something genuinely expensive and safe to share, like reading configuration, and @BeforeMethod to instantiate a new WebDriver before each test - since reusing one browser session across many tests risks leftover state (cookies, open modals) leaking from one test into the next, similar to the isolation problem Selenium tests need to guard against manually that other frameworks solve automatically through fresh contexts.
More Related questions...