wicket.util.tester
Class WicketTester

java.lang.Object
  extended by wicket.Application
      extended by wicket.protocol.http.WebApplication
          extended by wicket.protocol.http.MockWebApplication
              extended by wicket.util.tester.WicketTester
All Implemented Interfaces:
ISessionFactory

public class WicketTester
extends MockWebApplication

A helper to ease unit testing of Wicket applications without the need for a servlet container. To start a test, we can use either startPage() or startPanel():

 // production page  
 public class MyPage extends WebPage
 {
        public MyPage()
        {
                add(new Label("myMessage", "Hello!"));
                add(new Link("toYourPage")
                {
                        public void onClick()
                        {
                                setResponsePage(new YourPage("Hi!"));
                        }
                });
        }
 }
 
 // test code
 private WicketTester tester;
 
 public void setUp()
 {
        tester = new WicketTester();
 }
 
 public void testRenderMyPage()
 {
        //start and render the test page
        tester.startPage(MyPage.class);
 
        //assert rendered page class
        tester.assertRenderedPage(MyPage.class);
 
        //assert rendered label component 
        tester.assertLabel("myMessage", "Hello!");
 }
 
Above example is straight forward: start MyPage.class and assert Label it rendered. Next, we try to navigate through link:
 // production page  
 public class YourPage extends WebPage
 {
        public YourPage(String message)
        {
                add(new Label("yourMessage", message));
                info("Wicket Rocks ;-)");
        }
 }
 
 //test code
 public void testLinkToYourPage()
 {
        tester.startPage(MyPage.class);
 
        //click link and render
        tester.clickLink("toYourPage");
 
        tester.assertRenderedPage(YourPage.class);
        tester.assertLabel("yourMessage", "Hi!");
 }
 
tester.clickLink(path); will simulate user click on the component (in this case, it's a Link) and render the response page YourPage. Ok, unit test of MyPage is completed. Now we test YourPage standalone:
 //test code
 public void testRenderYourPage()
 {
        // provide page instance source for WicketTester
        tester.startPage(new TestPageSource()
        {
                public Page getTestPage()
                {
                        return new YourPage("mock message");
                }
        });
 
        tester.assertRenderedPage(YourPage.class);
        tester.assertLabel("yourMessage", "mock message");
 
        // assert feedback messages in INFO Level 
        tester.assertInfoMessages(new String[] { "Wicket Rocks ;-)" });
 
 }
 
Instead of tester.startPage(pageClass), we define a ITestPageSource to provide testing page instance for WicketTester. This is necessary because YourPage uses a custom constructor, which is very common for transfering model data, can not be instansiated by reflection. Finally, we use assertInfoMessages to assert there is a feedback message "Wicket Rocks ;-)" in INFO level. TODO General: Example usage of FormTester

Author:
Ingram Chen, Juergen Donnerstag, Frank Bille

Field Summary
 
Fields inherited from class wicket.Application
CONFIGURATION, CONTEXTPATH, DEPLOYMENT, DEVELOPMENT
 
Constructor Summary
WicketTester()
          create WicketTester with null path
WicketTester(java.lang.String path)
          create a WicketTester to help unit testing.
 
Method Summary
 void assertComponent(java.lang.String path, java.lang.Class expectedComponentClass)
          assert component class
 void assertComponentOnAjaxResponse(Component component)
          Test that a component has been added to a AjaxRequestTarget, using AjaxRequestTarget.addComponent(Component).
 void assertContains(java.lang.String pattern)
          assert the content of last rendered page contains(matches) regex pattern.
 void assertErrorMessages(java.lang.String[] expectedErrorMessages)
          assert error feedback messages
 void assertInfoMessages(java.lang.String[] expectedInfoMessages)
          assert info feedback message
 void assertInvisible(java.lang.String path)
          assert component invisible.
 void assertLabel(java.lang.String path, java.lang.String expectedLabelText)
          assert the text of Label component.
 void assertListView(java.lang.String path, java.util.List expectedList)
          assert the model of ListView use expectedList
 void assertNoErrorMessage()
          assert no error feedback messages
 void assertNoInfoMessage()
          assert no info feedback messages
 void assertPageLink(java.lang.String path, java.lang.Class expectedPageClass)
          assert PageLink link to page class.
 void assertRenderedPage(java.lang.Class expectedReneredPageClass)
          assert last rendered Page class
 void assertVisible(java.lang.String path)
          assert component visible.
 void clickLink(java.lang.String path)
          Click the Link in the last rendered Page.
 void clickLink(java.lang.String path, boolean isAjax)
          Click the Link in the last rendered Page.
 void debugComponentTrees()
          dump component tree
 void debugComponentTrees(java.lang.String filter)
          Dump the component trees to log.
 void dumpPage()
          dump the source of last rendered page
 void executeAjaxEvent(Component component, java.lang.String event)
          Simulate that an AJAX event has been fired.
 void executeAjaxEvent(java.lang.String componentPath, java.lang.String event)
          Simulate that an AJAX event has been fired.
 Component getComponentFromLastRenderedPage(java.lang.String path)
          Gets the component with the given path from last rendered page.
 java.util.List getMessages(int level)
          get feedback messages
 TagTester getTagById(java.lang.String id)
          Get a TagTester based on an dom id.
 TagTester getTagByWicketId(java.lang.String wicketId)
          Get a TagTester based on a wicket:id.
 FormTester newFormTester(java.lang.String path)
          create a FormTester for the form at path, and fill all child FormComponents with blank String initially.
 FormTester newFormTester(java.lang.String path, boolean fillBlankString)
          create a FormTester for the form at path.
 void setParameterForNextRequest(java.lang.String componentPath, java.lang.Object value)
          Sets a parameter for the component with the given path to be used with the next request.
 Page startPage(java.lang.Class pageClass)
          Render a page from its default constructor.
 Page startPage(ITestPageSource testPageSource)
          Render a page defined in TestPageSource.
 Page startPage(Page page)
          Render the page
 Panel startPanel(java.lang.Class panelClass)
          Render a panel from Panel(String id) constructor.
 Panel startPanel(TestPanelSource testPanelSource)
          Render a panel defined in TestPanelSource.
 void submitForm(java.lang.String path)
          submit the Form in the last rendered Page.
 
Methods inherited from class wicket.protocol.http.MockWebApplication
createRequestCycle, getHomePage, getLastRenderedPage, getParametersForNextRequest, getPreviousRenderedPage, getServletContext, getServletRequest, getServletResponse, getServletSession, getWicketRequest, getWicketResponse, getWicketSession, newSessionStore, processRequestCycle, processRequestCycle, processRequestCycle, setHomePage, setParametersForNextRequest, setupRequestAndResponse
 
Methods inherited from class wicket.protocol.http.WebApplication
getApplicationKey, getDefaultRequestCycleFactory, getRequestCycleProcessor, getRequestLogger, getSessionAttributePrefix, getSessionFactory, getWicketServlet, init, internalDestroy, internalInit, logEventTarget, logResponseTarget, mount, mount, mountBookmarkablePage, mountBookmarkablePage, mountBookmarkablePage, mountSharedResource, newRequestCycleProcessor, newSession, newWebRequest, newWebResponse, sessionDestroyed, setApplicationKey, setRequestLogger, setSessionFactory, setWicketServlet, unmount
 
Methods inherited from class wicket.Application
addComponentInstantiationListener, configure, configure, configure, destroy, exists, get, get, getAjaxSettings, getApplicationSettings, getConfigurationType, getDebugSettings, getExceptionSettings, getFrameworkSettings, getMarkupCache, getMarkupSettings, getMetaData, getName, getPageSettings, getRequestCycleSettings, getResourceSettings, getSecuritySettings, getSessionSettings, getSessionStore, getSettings, getSharedResources, initializeComponents, isAttached, removeComponentInstantiationListener, set, setMetaData, unset
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

WicketTester

public WicketTester()
create WicketTester with null path

See Also:
WicketTester(String)

WicketTester

public WicketTester(java.lang.String path)
create a WicketTester to help unit testing.

Parameters:
path - The absolute path on disk to the web application contents (e.g. war root) - may be null
See Also:
MockWebApplication.MockWebApplication(String)
Method Detail

startPage

public final Page startPage(ITestPageSource testPageSource)
Render a page defined in TestPageSource. This usually used when a page does not have default consturctor. For example, a ViewBook page requires a Book instance:
 tester.startPage(new TestPageSource()
 {
        public Page getTestPage()
        {
                Book mockBook = new Book("myBookName");
                return new ViewBook(mockBook);
        }
 });
 

Parameters:
testPageSource - a page factory that creating test page instance
Returns:
Page rendered page

startPage

public final Page startPage(Page page)
Render the page

Parameters:
page -
Returns:
The page rendered

startPage

public final Page startPage(java.lang.Class pageClass)
Render a page from its default constructor.

Parameters:
pageClass - a test page class with default constructor
Returns:
Page Rendered Page

startPanel

public final Panel startPanel(TestPanelSource testPanelSource)
Render a panel defined in TestPanelSource. The usage is similar with startPage(ITestPageSource). Please note that testing panel must use supplied panelId as component id.
 tester.startPanel(new TestPanelSource()
 {
        public Panel getTestPanel(String panelId)
        {
                MyData mockMyData = new MyData();
                return new MyPanel(panelId, mockMyData);
        }
 });
 

Parameters:
testPanelSource - a panel factory that creating test panel instance
Returns:
Panel rendered panel

startPanel

public final Panel startPanel(java.lang.Class panelClass)
Render a panel from Panel(String id) constructor.

Parameters:
panelClass - a test panel class with Panel(String id) constructor
Returns:
Panel rendered panel

getComponentFromLastRenderedPage

public Component getComponentFromLastRenderedPage(java.lang.String path)
Gets the component with the given path from last rendered page. This method fails in case the component couldn't be found, and it will return null if the component was found, but is not visible.

Parameters:
path - Path to component
Returns:
The component at the path
See Also:
MarkupContainer.get(String)

assertLabel

public void assertLabel(java.lang.String path,
                        java.lang.String expectedLabelText)
assert the text of Label component.

Parameters:
path - path to Label component
expectedLabelText - expected label text

assertPageLink

public void assertPageLink(java.lang.String path,
                           java.lang.Class expectedPageClass)
assert PageLink link to page class.

Parameters:
path - path to PageLink component
expectedPageClass - expected page class to link

assertComponent

public void assertComponent(java.lang.String path,
                            java.lang.Class expectedComponentClass)
assert component class

Parameters:
path - path to component
expectedComponentClass - expected component class

assertVisible

public void assertVisible(java.lang.String path)
assert component visible.

Parameters:
path - path to component

assertInvisible

public void assertInvisible(java.lang.String path)
assert component invisible.

Parameters:
path - path to component

assertContains

public void assertContains(java.lang.String pattern)
assert the content of last rendered page contains(matches) regex pattern.

Parameters:
pattern - reqex pattern to match

assertListView

public void assertListView(java.lang.String path,
                           java.util.List expectedList)
assert the model of ListView use expectedList

Parameters:
path - path to ListView component
expectedList - expected list in the model of ListView

newFormTester

public FormTester newFormTester(java.lang.String path)
create a FormTester for the form at path, and fill all child FormComponents with blank String initially.

Parameters:
path - path to Form component
Returns:
FormTester A FormTester instance for testing form
See Also:
newFormTester(String, boolean)

newFormTester

public FormTester newFormTester(java.lang.String path,
                                boolean fillBlankString)
create a FormTester for the form at path.

Parameters:
path - path to Form component
fillBlankString - specify whether fill all child FormComponents with blankString initially.
Returns:
FormTester A FormTester instance for testing form
See Also:
FormTester

clickLink

public void clickLink(java.lang.String path)
Click the Link in the last rendered Page.

Simulate that AJAX is enabled.

Parameters:
path - Click the Link in the last rendered Page.
See Also:
clickLink(String, boolean)

clickLink

public void clickLink(java.lang.String path,
                      boolean isAjax)
Click the Link in the last rendered Page.

This method also works for AjaxLink, AjaxFallbackLink and AjaxSubmitLink.

On AjaxLinks and AjaxFallbackLinks the onClick method is invoked with a valid AjaxRequestTarget. In that way you can test the flow of your application when using AJAX.

When clicking an AjaxSubmitLink the form, which the AjaxSubmitLink is attached to is first submitted, and then the onSubmit method on AjaxSubmitLink is invoked. If you have changed some values in the form during your test, these will also be submitted. This should not be used as a replacement for the FormTester to test your forms. It should be used to test that the code in your onSubmit method in AjaxSubmitLink actually works.

This method is also able to simulate that AJAX (javascript) is disabled on the client. This is done by setting the isAjax parameter to false. If you have an AjaxFallbackLink you can then check that it doesn't fail when invoked as a normal link.

Parameters:
path - path to Link component
isAjax - Whether to simulate that AJAX (javascript) is enabled or not. If it's false then AjaxLink and AjaxSubmitLink will fail, since it wouldn't work in real life. AjaxFallbackLink will be invoked with null as the AjaxRequestTarget parameter.

submitForm

public void submitForm(java.lang.String path)
submit the Form in the last rendered Page.

Parameters:
path - path to Form component

setParameterForNextRequest

public void setParameterForNextRequest(java.lang.String componentPath,
                                       java.lang.Object value)
Sets a parameter for the component with the given path to be used with the next request. NOTE: this method only works when a page was rendered first.

Parameters:
componentPath - path of the component
value - the parameter value to set

assertRenderedPage

public void assertRenderedPage(java.lang.Class expectedReneredPageClass)
assert last rendered Page class

Parameters:
expectedReneredPageClass - expected class of last renered page

assertNoErrorMessage

public void assertNoErrorMessage()
assert no error feedback messages


assertNoInfoMessage

public void assertNoInfoMessage()
assert no info feedback messages


assertErrorMessages

public void assertErrorMessages(java.lang.String[] expectedErrorMessages)
assert error feedback messages

Parameters:
expectedErrorMessages - expected error messages

assertInfoMessages

public void assertInfoMessages(java.lang.String[] expectedInfoMessages)
assert info feedback message

Parameters:
expectedInfoMessages - expected info messages

getMessages

public java.util.List getMessages(int level)
get feedback messages

Parameters:
level - level of feedback message, ex. FeedbackMessage.DEBUG or FeedbackMessage.INFO.. etc
Returns:
List list of messages (in String)
See Also:
FeedbackMessage

dumpPage

public void dumpPage()
dump the source of last rendered page


debugComponentTrees

public void debugComponentTrees()
dump component tree


debugComponentTrees

public void debugComponentTrees(java.lang.String filter)
Dump the component trees to log.

Parameters:
filter - Show only the components, which path contains the filterstring.

assertComponentOnAjaxResponse

public void assertComponentOnAjaxResponse(Component component)
Test that a component has been added to a AjaxRequestTarget, using AjaxRequestTarget.addComponent(Component). This method actually tests that a component is on the AJAX response sent back to the client.

PLEASE NOTE! This method doesn't actually insert the component in the client DOM tree, using javascript. But it shouldn't be needed because you have to trust that the Wicket Ajax Javascript just works.

Parameters:
component - The component to test whether it's on the response.

executeAjaxEvent

public void executeAjaxEvent(java.lang.String componentPath,
                             java.lang.String event)
Simulate that an AJAX event has been fired.

Parameters:
componentPath - The component path.
event - The event which we simulate is fired. If the event is null, the test will fail.
Since:
1.2.3
See Also:
executeAjaxEvent(Component, String)

executeAjaxEvent

public void executeAjaxEvent(Component component,
                             java.lang.String event)
Simulate that an AJAX event has been fired. You add an AJAX event to a component by using:
    ...
    component.add(new AjaxEventBehavior("ondblclick") {
        public void onEvent(AjaxRequestTarget) {
            // Do something.
        }
    });
    ...
 
You can then test that the code inside onEvent actually does what it's supposed to, using the WicketTester:
    ...
    tester.executeAjaxEvent(component, "ondblclick");
              
    // Test that the code inside onEvent is correct.
    ...
 
This also works with AjaxFormSubmitBehavior, where it will "submit" the form before executing the command.

PLEASE NOTE! This method doesn't actually insert the component in the client DOM tree, using javascript.

Parameters:
component - The component which has the AjaxEventBehavior we wan't to test. If the component is null, the test will fail.
event - The event which we simulate is fired. If the event is null, the test will fail.

getTagByWicketId

public TagTester getTagByWicketId(java.lang.String wicketId)
Get a TagTester based on a wicket:id. If more components exists with the same wicket:id in the markup only the first one is returned.

Parameters:
wicketId - The wicket:id to search for.
Returns:
The TagTester for the tag which has the given wicket:id.

getTagById

public TagTester getTagById(java.lang.String id)
Get a TagTester based on an dom id. If more components exists with the same id in the markup only the first one is returned.

Parameters:
id - The dom id to search for.
Returns:
The TagTester for the tag which has the given dom id.


Copyright © 2004-2007 Wicket developers. All Rights Reserved.