Add new tag
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.
Search
Subscribe
Recent Posts
Tags
Archives
- Heading to #alancon in Dublin this weekend. Frames, marquee, font tags, oh my! 3 days ago
- List the dimensions of images in a directory with identify -format '%f %w %h\n' *.jpg Outputs: mypic.jpg 200 450 4 days ago
- .@rem on the cover of net magazine, should make for good plane reading http://twitpic.com/28j8u2 6 days ago
- More updates...