import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import org.junit.Assert; import org.junit.Test; public class SimpleTest { @Test public void testTitle() { WebDriver driver = new ChromeDriver(); driver.get("https://example.com"); String title = driver.getTitle(); Assert.assertEquals("Example Domain", title); driver.quit(); } }
The test opens the URL https://example.com, which has the title "Example Domain". The assertion checks if the title matches exactly, so the test passes. The driver is closed properly with driver.quit(). No element lookup is done, so no NoSuchElementException occurs.
Using By.id("loginBtn") is best because IDs are unique and stable. Class names may be shared by multiple elements. XPath and CSS selectors are more complex and less efficient here.
WebElement message = driver.findElement(By.id("successMsg"));
String text = message.getText();Using assertTrue with text.contains ensures the message includes the expected text even if there is extra content. assertEquals would fail if the text is not exactly the same.
If the element is inside an iframe, Selenium cannot find it until you switch the driver's context to that iframe. This causes NoSuchElementException.
@BeforeClass runs once before all tests, @Before runs before each test, @Test is the test method, @After runs after each test, and @AfterClass runs once after all tests.