20 Test Driven Development with Wicket - Reference Documentation
Authors: Andrea Del Bene, Carsten Hufe, Christian Kroemer, Daniel Bartl
Version: 1.0.0.BUILD-SNAPSHOT
Table of Contents
20 Test Driven Development with Wicket
Test Driven Development has become a crucial activity for every modern development methodology. This chapter will cover the built-in support for testing provided by Wicket with its rich set of helper and mock classes that allows us to test our components and our applications in isolation (i.e without the need for a servlet container) using JUnit, the de facto standard for Java unit testing.In this chapter we will see how to write unit tests for our applications and components and we will learn how to use helper classes to simulate user navigation and write acceptance tests without the need of any testing framework other than JUnit.The JUnit version used in this chapter is 4.x.20.1 Utility class WicketTester
A good way to start getting confident with Wicket unit testing support is looking at the test case class TestHomePage that is automatically generated by Maven when we use Wicket archetype to create a new project:Here is the content of TestHomePage:public class TestHomePage{ private WicketTester tester; @Before public void setUp(){ tester = new WicketTester(new WicketApplication()); } @Test public void homepageRendersSuccessfully(){ //start and render the test page tester.startPage(HomePage.class); //assert rendered page class tester.assertRenderedPage(HomePage.class); } }
Testing links
A click on a Wicket link can be simulated with method clickLink which takes in input the link component or the page-relative path to it.To see an example of usage of clickLink, let's consider again project LifeCycleStagesRevisited. As we know from chapter 5 the home page of the project alternately displays two different labels (“First label” and “Second label”), swapping between them each time button "reload" is clicked. The code from its test case checks that label has actually changed after button "reload" has been pressed://… @Test public void switchLabelTest(){ //start and render the test page tester.startPage(HomePage.class); //assert rendered page class tester.assertRenderedPage(HomePage.class); //assert rendered label tester.assertLabel("label", "First label"); //simulate a click on "reload" button tester.clickLink("reload"); //assert rendered label tester.assertLabel("label", "Second label"); } //...
//… //simulate a click on a button without AJAX support tester.clickLink("reload", false); //...
Testing component status
WicketTester provides also a set of methods to test the states of a component. They are:- assertEnabled(String path)/assertDisabled(String path): they test if a component is enabled or not.
- assertVisible(String path)/assertInvisible(String path): they test component visibility.
- assertRequired(String path): checks if a form component is required.
//… @Test public void testDisableDatePickerWithButton(){ //start and render the test page tester.startPage(HomePage.class); //assert that datepicker is enabled tester.assertEnabled("form:datepicker"); //click on update button to disable datepicker tester.clickLink("update"); //assert that datepicker is disabled tester.assertDisabled("form:datepicker"); } //...
Testing components in isolation
Method startComponent(Component) can be used to test a component in isolation without having to create a container page for this purpose. The target component is rendered and both its methods onInitialize() and onBeforeRender() are executed. In the test case from project CustomFormComponentPanel we used this method to check if our custom form component correctly renders its internal label://… @Test public void testCustomPanelContainsLabel(){ TemperatureDegreeField field = new TemperatureDegreeField("field", Model.of(0.00)); //Use standard JUnit class Assert Assert.assertNull(field.get("mesuramentUnit")); tester.startComponent(field); Assert.assertNotNull(field.get("mesuramentUnit")); } //...
Testing the response
WicketTester allows us to access to the last response generated during testing with method getLastResponse. The returned value is an instance of class MockHttpServletResponse that provides helper methods to extract informations from mocked request.In the test case from project CustomResourceMounting we extract the text contained in the last response with method getDocument and we check if it is equal to the RSS feed used for the test://… @Test public void testMountedResourceResponse() throws IOException, FeedException{ tester.startResource(new RSSProducerResource()); String responseTxt = tester.getLastResponse().getDocument(); //write the RSS feed used in the test into a ByteArrayOutputStream ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); Writer writer = new OutputStreamWriter(outputStream); SyndFeedOutput output = new SyndFeedOutput(); output.output(RSSProducerResource.getFeed(), writer); //the response and the RSS must be equal Assert.assertEquals(responseTxt, outputStream.toString()); } //...
Testing URLs
WicketTester can be pointed to an arbitrary URL with method executeUrl(String url). This can be useful to test mounted pages, resources or request mappers://…
//the resource was mapped at '/foo/bar'
tester.executeUrl("./foo/bar");
//...
Testing AJAX components
If our application uses AJAX to refresh components markup, we can test if AjaxRequestTarget contains a given component with WicketTester's method assertComponentOnAjaxResponse://… //test if AjaxRequestTarget contains a component (using its instance) tester.assertComponentOnAjaxResponse(amountLabel); //… //test if AjaxRequestTarget contains a component (using its path) tester.assertComponentOnAjaxResponse("pathToLabel:labelId");
//…
//test if AjaxRequestTarget does NOT contain amountLabel
assertFalse(tester.isComponentOnAjaxResponse(amountLabel));
//...
Testing AJAX events
Behavior AjaxEventBehavior and its subclasses can be tested simulating AJAX events with WicketTester's method executeAjaxEvent(Component cmp, String event). Here is the sample code from project TestAjaxEventsExample:Home page code:public class HomePage extends WebPage { public static String INIT_VALUE = "Initial value"; public static String OTHER_VALUE = "Other value"; public HomePage(final PageParameters parameters) { super(parameters); Label label; add(label = new Label("label", INIT_VALUE)); label.add(new AjaxEventBehavior("click") { @Override protected void onEvent(AjaxRequestTarget target) { //change label's data object getComponent().setDefaultModelObject(OTHER_VALUE); target.add(getComponent()); } }).setOutputMarkupId(true); //… } }
@Test public void testAjaxBehavior(){ //start and render the test page tester.startPage(HomePage.class); //test if label has the initial expected value tester.assertLabel("label", HomePage.INIT_VALUE); //simulate an AJAX "click" event tester.executeAjaxEvent("label", "click"); //test if label has changed as expected tester.assertLabel("label", HomePage.OTHER_VALUE); }
Testing AJAX behaviors
To test a generic AJAX behavior we can simulate a request to it using WicketTester's method executeBehavior(AbstractAjaxBehavior behavior)://… AjaxFormComponentUpdatingBehavior ajaxBehavior = new AjaxFormComponentUpdatingBehavior ("change"){ @Override protected void onUpdate(AjaxRequestTarget target) { //... } }; component.add(ajaxBehavior); //… //execute AJAX behavior, i.e. onUpdate will be invoked tester.executeBehavior(ajaxBehavior)); //...
Using a custom servlet context
In paragraph 13.9 we have seen how to configure our application to store resource files into a custom folder placed inside webapp root folder (see project CustomFolder4MarkupExample).In order to write testing code for applications that use this kind of customization, we must tell WicketTester which folder to use as webapp root. This is necessary as under test environment we don't have any web server, hence it's impossible for WicketTester to retrieve this parameter from servlet context.Webapp root folder can be passed to WicketTester's constructor as further parameter like we did in the test case of project CustomFolder4MarkupExample:public class TestHomePage{ private WicketTester tester; @Before public void setUp(){ //build the path to webapp root folder File curDirectory = new File(System.getProperty("user.dir")); File webContextDir = new File(curDirectory, "src/main/webapp"); tester = new WicketTester(new WicketApplication(), webContextDir.getAbsolutePath()); } //test methods… }
After a test method has been executed, we may need to clear any possible side effect occurred to the Application and Session objects. This can be done invoking WicketTester's method destroy():@After public void tearDown(){ //clear any side effect occurred during test. tester.destroy(); }
20.2 Testing Wicket forms
Wicket provides utility class FormTester that is expressly designed to test Wicket forms. A new FormTester is returned by WicketTester's method newFormTester(String, boolean) which takes in input the page-relative path of the form we want to test and a boolean flag indicating if its form components must be filled with a blank string://… //create a new form tester without filling its form components with a blank string FormTester formTester = tester.newFormTester("form", false); //...
//… //create a new form tester without filling its form components with a blank string FormTester formTester = tester.newFormTester("form", false); //submit form with default submitter formTester.submit(); //… //submit form using inner component 'button' as alternate button formTester.submit("button");
Setting form components input
The purpose of a HTML form is to collect user input. FormTester comes with the following set of methods that simulate input insertion into form's fields:- setValue(String path, String value): inserts the given textual value into the specified component. It can be used with components TextField and TextArea. A version of this method that accepts a component instance instead of its path is also available.
- setValue(String checkboxId, boolean value): sets the value of a given CheckBox component.
- setFile(String formComponentId, File file, String contentType): sets a File object on a FileUploadField component.
- select(String formComponentId, int index): selects an option among a list of possible options owned by a component. It supports components that are subclasses of AbstractChoice along with RadioGroup and CheckGroup.
- selectMultiple(String formComponentId, int indexes): selects all the options corresponding to the given array of indexes. It can be used with multiple-choice components like CheckGroup or ListMultipleChoice.
protected void insertUsernamePassword(String username, String password) { //start and render the test page tester.startPage(HomePage.class); FormTester formTester = tester.newFormTester("form"); //set credentials formTester.setValue("username", username); formTester.setValue("password", password); //submit form formTester.submit(); }
Testing feedback messages
To check if a page contains one or more expected feedback messages we can use the following methods provided by WicketTester:- assertFeedback(String path, String… messages): asserts that a given panel contains the specified messages
- assertInfoMessages(String… expectedInfoMessages): asserts that the expected info messages are rendered in the page.
- assertErrorMessages(String… expectedErrorMessages): asserts that the expected error messages are rendered in the page.
@Test public void testMessageForSuccessfulLogin(){ inserUsernamePassword("user", "user"); tester.assertInfoMessages("Username and password are correct!"); }@Test public void testMessageForFailedLogin (){ inserUsernamePassword("wrongCredential", "wrongCredential"); tester.assertErrorMessages("Wrong username or password"); }
Testing models
Component model can be tested as well. With method assertModelValue we can test if a specific component has the expected data object inside its model.This method has been used in the test case of project ModelChainingExample to check if the form and the drop-down menu share the same data object:@Test public void testFormSelectSameModelObject(){ PersonListDetails personListDetails = new PersonListDetails(); DropDownChoice dropDownChoice = (DropDownChoice) personListDetails.get("persons"); List choices = dropDownChoice.getChoices(); //select the second option of the drop-down menu dropDownChoice.setModelObject(choices.get(1)); //start and render the test page tester.startPage(personListDetails); //assert that form has the same data object used by drop-down menu tester.assertModelValue("form", dropDownChoice.getModelObject()); }
20.3 Testing markup with TagTester
If we need to test component markup at a more fine-grained level, we can use class TagTester from package org.apache.wicket.util.tester.This test class allows to check if the generated markup contains one or more tags having a given attribute with a given value. TagTester can not be directly instantiated but it comes with three factory methods that return one or more TagTester matching the searching criteria. In the following test case (from project TagTesterExample) we retrieve the first tag of the home page (a <span> tag) having attribute class equal to myClass:HomePage markup:<html xmlns:wicket="http://wicket.apache.org"> <head> <meta charset="utf-8" /> <title></title> </head> <body> <span class="myClass"></span> <div class="myClass"></div> </body> </html>
@Test public void homePageMarkupTest() { //start and render the test page tester.startPage(HomePage.class); //retrieve response's markup String responseTxt = tester.getLastResponse().getDocument(); TagTester tagTester = TagTester.createTagByAttribute(responseTxt, "class", "myClass"); Assert.assertNotNull(tagTester); Assert.assertEquals("span", tagTester.getName()); List<TagTester> tagTesterList = TagTester.createTagsByAttribute(responseTxt, "class", "myClass", false); Assert.assertEquals(2, tagTesterList.size()); }