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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
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:
1 2 3 4 5 6 7 8 9 10 11
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
There you have it, a simple Eclipse template to generate your BDDMockito style tests.