### Question:
UniqueLabelForFormElementRule extends AbstractRule { @Override protected void applyTo(Page page, Violations violations) { List<HtmlLabel> labels = page.findAllLabelTags(); for (HtmlLabel label : labels) { if (!exactlyOneLabelWithGivenForAttribute(labels, label.getForAttribute())) { violations.add(createViolation(label, page, RULE_MESSAGE)); } } }  @Override String getName();  }### Answer:
@Test public void singleLabelForFormElement() throws Exception { String content = "<html>" + "<body>" + " <form>" + " <label for=\"username\">Username</label>" + " <input type=\"text\" name=\"username\" id=\"username\" />" + " </form>" + "</body>" + "</html>"; Violations violations = rule.applyTo(toHtmlPage(content)); assertNoViolations(violations, rule); }
@Test public void twoLabelsForTwoDifferentFormElements() throws Exception { String content = "<html>" + "<body>" + " <form>" + " <label for=\"username\">Username</label>" + " <input type=\"text\" name=\"username\" id=\"username\" />" + " <label for=\"password\">Password</label>" + " <input type=\"password\" name=\"password\" id=\"password\" />" + " </form>" + "</body>" + "</html>"; Violations violations = rule.applyTo(toHtmlPage(content)); assertNoViolations(violations, rule); }
@Test public void duplicateLabelForFormElement() throws Exception { String content = "<html>" + "<body>" + " <form>" + " <label for=\"username\">Username</label>" + " <input type=\"text\" name=\"username\" id=\"username\" />" + " <label for=\"username\">Your Username</label>" + " </form>" + "</body>" + "</html>"; Violations violations = rule.applyTo(toHtmlPage(content)); assertViolations(violations, rule, 2); }