This test opens a webpage, finds a checkbox by its ID, selects it if not already selected, prints the action, and asserts the checkbox is selected.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class CheckboxTest {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "path/to/chromedriver");
WebDriver driver = new ChromeDriver();
try {
driver.get("https://example.com/form");
WebElement checkbox = driver.findElement(By.id("agreeTerms"));
// Check if checkbox is selected
if (!checkbox.isSelected()) {
checkbox.click();
System.out.println("Checkbox was not selected, now selected.");
} else {
System.out.println("Checkbox was already selected.");
}
// Verify checkbox is selected
assert checkbox.isSelected() : "Checkbox should be selected after clicking.";
} finally {
driver.quit();
}
}
}