BDDMockito & Eclipse
On the 23rd of July, Mockito 1.8.0 was released, you can see a full listing of changes in their release notes. One feature that took my fancy was the inclusion of BDD aliases for stubbing an API, instead of using when, the Mockito team now encourage the use of given to bring your tests inline with the BDD style. To illustrate this, here is an example taken from the BDDMockito javadoc.
Seller seller = mock(Seller.class);
Shop shop = new Shop(seller);
public void shouldBuyBread() throws Exception {
//given
given(seller.askForBread()).willReturn(new Bread());
//when
Goods goods = shop.buyBread();
//then
assertThat(goods, containBread());
}
By breaking the test into given, when & then, future maintainers of the tests will more quickly understand which parts of the test relate to setup, exercising the SUT and asserting.
(stealing from Apple’s AppStore ad) What’s great about Eclipse, is that if you want to write a foreach loop, there’s a template for that. If you want to create a unit test, there’s a template for that. Yip there’s an app template for just about anything.
To minimise keystrokes and encourage the use of this style, you can modify the existing Test template as shown below to automatically generate the BDD style comments & statically import the BDDMockito members. To modify the template, navigate to Window > Preferences > Java > Editor > Templates. Click on Test (the JUnit 4 test template) and click edit. Paste in the follow template:
public void ${testname}() throws Exception {
// given ${cursor}
${staticImport:importStatic('org.junit.Assert.*', 'org.mockito.BDDMockito.*')}
// when
// then
}
You are now ready to start writing BDDMockito style unit tests using Eclipse’s template, simply type Test, hit Ctrl+Space and you will be given the following option.

Selecting the option will generate the test method, focus first given to the test name, then to the blank line after // given.

There you have it, a simple Eclipse template to generate your BDDMockito style tests.
3 Comments to BDDMockito & Eclipse
After using this style for a few of day I’ve updated the eclipse template slightly. The position of the cursor should be on the same line as the given text.
This allows you to write the description of the context.
e.g.
// given a user with first name John and last name Smith
…
// when we get their full name
…
// then John Smith should be returned
…
September 8, 2009
Thanks! Nice stuff
I’ve now aliased the Test template to ’should’ as I generally name my examples as shouldDoSomething.
Leave a comment
Search
Subscribe
Recent Posts
Tags
Archives
What I'm Doing...
- Missed my tube stop playing Archipelago, sign of a compelling game. If only it had multiplayer #android 3 hrs ago
- Beautiful website too! RT @aalmiray http://nosqleu.com/ is the place to be if you care about #nosql 1 day ago
- (2008..new Date()[Calendar.YEAR]).each() {} #lovingthegroovy 2 days ago
- More updates...
August 18, 2009