JUnit is lovely. HtmlUnit is really nice too. Combined, they allow for quite nice automated web application testing. There are even a number of things built on top of HtmlUnit to make test cases more concise and easier to read and write. But that only as an aside.
This last weekend I have tried out HtmlUnit for the first time (wanted to do this for a while). I have integrated it with the Little Portal Gizmo to help testing Gizmo based web applications.
Below is a test class with a single test method.
public class WebTests {
// First, the web application service is fired up (we
// wait 500 ms after kicking it off).
@BeforeClass
public static void setUpBeforeClass() throws Exception {
PortalTest.startPortal(500);
}
// Now the actual test...
@Test
public void loginLogoutGetSession() throws Exception {
// Start off with logging the user in. This is a client-side activity:
// get the login page, fill in the fields and click the button.
WebClient cl = new WebClient();
HtmlPage pg = cl.getPage("http://127.0.0.1:8080/todo");
assertEquals("Login", pg.getTitleText());
HtmlForm login = pg.getFormByName("input");
login.getInputByName("user").setValueAttribute("jimmy");
login.getInputByName("password").setValueAttribute("jimmy");
HtmlPage loggedIn = login.getInputByName("button").click();
// After successful login we now inspect the application on
// the server and extract the session object from it that corresponds
// to the login activity above. We can do this very easily because
// the web application runs in the same JVM as the test code.
ToDoSession s = (ToDoSession) PortalTest.getSessionForPage(loggedIn);
assertEquals("jimmy", s.getUser().getName());
assertEquals("jimmy", s.getUser().getPasswd());
// Now we log out. This will remove the session from the server
// application's session map.
HtmlPage logout = loggedIn.getAnchorByHref("logout").click();
assertEquals("Logout", logout.getTitleText());
// Trying to get the session again will return a null reference.
assertNull(PortalTest.getSessionForPage(loggedIn));
}
}
The above example of a test shows how both server side and client side are visible inside the test code and can easily be accessed. I find this very useful. What do you think? How do your tests look like?
How nice! I’m looking forward to try this out. And it looks simple too, I wonder how this works with async tests though.