This example shows how to test a form with an AJAX enabled check box in it. When you click the check box, a greeting is displayed.
Message: [Message]
The code illustrates the following, less easy concepts.
To simulate that the user clicks the check box, we do executeAjaxEvent. Here is the code snippet:
// Get this right or get "No AjaEventBehavior found ..." static final String CHECKBOX_EVENT = "onclick"; private FormTester fillInTheForm() { FormTester formTester = tester.newFormTester(CheckBoxPage.FORM); formTester.setValue(CheckBoxPage.CHECK_BOX, true); String pathToCheckBox = CheckBoxPage.FORM + ":" + CheckBoxPage.CHECK_BOX; tester.executeAjaxEvent(pathToCheckBox, CHECKBOX_EVENT); return formTester; }
Note that we do not do a form submit and execute an event in the same test case. It seems to stir up unnecessary evil.
A mistake that is possible, is to forget to add a component to the AJAX request when the component is updated.
In our example it is the label that should be updated with a message when the check box is clicked.
Unless we do anything to check this, the omission will go unnoticed through the test. Here we solve this by putting the AJAX update in a protected method in the page class.
During testing, we subclass the page and override that method. In the method, we take the chance to note how many times we are called and whether the component added has its mark-up set. The latter is also an omission that will go unnoticed until somebody runs the site in a browser.
Here is the code.
class CheckBoxPageAjaxOverride extends CheckBoxPage implements Serializable { static final String FORGOT_TO_CALL_SET_MARKUP_ID = "You forgot to call setMarkupId(true) on '%s'"; int ajaxCalled = 0; @Override protected void ajaxUpdate(AjaxRequestTarget target, Component comp) { super.ajaxUpdate(target, comp); ajaxCalled++; String failMessage = String.format(FORGOT_TO_CALL_SET_MARKUP_ID, comp.getId()); assertNotNull(failMessage, comp.getMarkupId(false)); } ... private void assertOnlyTheMessageIsDisplayed(CheckBoxPageAjaxOverride testPage, String expected, String actual) { assertEquals(expected, actual); assertEquals(1, testPage.ajaxCalled); tester.assertNoErrorMessage(); }
Note that we check that the correct message is displayed, that AJAX request was done properly and that there are no error messages. If somebody later adds a required field to the page, our test will notice that we did not fill in that new field.