Stories, software, and a life lived across several worlds
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 {
@Mock
private CategoryRepository categoryRepository ;
@Test
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.
| Previous | 30 Dec 2009 | Next |
About me
Hello! My name is Stephan Schwab.
I build and rescue software, and I write fiction about the human side of how it gets made. Here you’ll find my stories and novelas, notes on craft, and field notes from a life lived across several worlds.
Working with software teams is what I do professionally — see how on caimito.net. You can also read about my experience since 1986.
Work with me
Hire me as the senior who embeds in your team and makes it ship.
Stories & writing
On the craft
Life across several worlds
Places that shaped me
Open Source
Stay in touch
LinkedIn Mastodon Bluesky TikTok Twitter RSS Email
Everything
See a listing of all posts on this site.