Tales about Aviation, Coaching, Farming, Software Development

Using EasyMock to unit test Tapestry components and pages

Currently I’m working on a client project where we use Tapestry 5.1 as our web framework. We want to test well so we are using Tapestry’s PageTester to write unit tests for pages and components. If you do that, you’ll quickly run into the issue of how to inject services into your pages and components without creating an application module in each and every test class.

A while back Russell Brown posted on the Tapestry mailing list a description of a simple solution to this. In November Russell and I emailed and he was kind enough to share his solution on gist.github.com.

This is an example of how I use it in a unit test for a component:

public class ProductsInCategoryDisplayTest {

  private CategoryRepository categoryRepository ;

  public void getProductsForCategory() {
    ProductsInCategoryDisplay display = new ProductsInCategoryDisplay() ;
    Category selectedCategory = new Category(1, "Category", "SEO Text for Category") ;
    EasyMockHelper helper = new EasyMockHelper(this, display) ;
    EasyMock.expect(categoryRepository.getCategoryProducts(selectedCategory, true, null)).andStubReturn(new ArrayList()) ;
    helper.replayMocks() ;

    display.setCategory(selectedCategory) ;
    Collection products = display.getProducts() ;
    assertNotNull(products) ;


The @Mock annotation marks CategoryRepository as something that should be mocked and injected. new EasyMockHelper(this, display) lets the helper know that it should look for mocks in the test class and that display is the place where to inject them into.

The rest is regular setting of expectations for EasyMock. Finally the helper gets told to replay the mocks and the it all works.