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 junit.framework.TestCase;
public class SearchExample extends TestCase {
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 net.sourceforge.jwebunit.util.TestingEngineRegistry;
import net.sourceforge.jwebunit.junit.WebTestCase;
public class SearchExample extends WebTestCase {
public void setUp() {
setTestingEngineKey(TestingEngineRegistry.TESTING_ENGINE_HTMLUNIT);
getTestContext().setBaseUrl("http://www.google.com");
}
public void testSearch() throws Exception {
beginAt("/");
setTextField("q", "htmlunit");
submit("btnG");
clickLinkWithText("HtmlUnit");
assertTitleEquals("htmlunit - Welcome to HtmlUnit");
assertLinkPresentWithText("Get started");
}
}
|