HtmlUnit plugin
The following sample testcases illustrate the conciseness of JWebUnit versus HtmlUnit and JUnit alone. The tests perform a google search for the HtmlUnit home page, navigate to that page from Google, and validate that there is a link to the user manual on the HtmlUnit home page. The code in the first column is pure HtmlUnit / JUnit, while the second column uses the JWebUnit framework.
| JUnit/HtmlUnit Test | JWebUnit Test |
|---|---|
import java.net.URL;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlSubmitInput;
import com.gargoylesoftware.htmlunit.html.HtmlTextInput;
import org.junit.Test;
public class SearchExample {
@Test
public void testSearch() throws Exception {
final WebClient webClient = new WebClient();
final URL url = new URL("http://www.google.com");
final HtmlPage page = (HtmlPage)webClient.getPage(url);
HtmlForm form = (HtmlForm) page.getForms().get(0);
HtmlTextInput text = (HtmlTextInput) form.getInputByName("q");
text.setValueAttribute("HtmlUnit");
HtmlSubmitInput btn = (HtmlSubmitInput) form.getInputByName("btnG");
HtmlPage page2 = (HtmlPage) btn.click();
HtmlAnchor link = page2.getAnchorByHref("http://htmlunit.sourceforge.net/");
HtmlPage page3 = (HtmlPage) link.click();
assertEquals(page3.getTitleText(), "htmlunit - Welcome to HtmlUnit");
assertNotNull(page3.getAnchorByHref("gettingStarted.html"));
}
}
|
import org.junit.Before;
import org.junit.Test;
import static net.sourceforge.jwebunit.junit.JWebUnit.*;
public class SearchExample {
@Before
public void prepare() {
setBaseUrl("http://www.google.com");
}
@Test
public void testSearch() {
beginAt("/");
setTextField("q", "htmlunit");
submit("btnG");
clickLinkWithText("HtmlUnit");
assertTitleEquals("htmlunit - Welcome to HtmlUnit");
assertLinkPresentWithText("Get started");
}
}
|