Simple JUnit4 templates for Eclipse

March 20, 2012 | 1 min Read

JUnit and Eclipse are a great combination, but one thing that I missed every time I worked with JUnit4 was the code templates. Currently, Eclipse ships with pre-defined templates for JUnit3 but not for JUnit4. So, I wrote three basic JUnit4 templates that can be imported from the “Templates” Preference Page. Take a look at the screenshot below to see how to get there. The templates are called test, setup and teardown. They all create method stubs with the right Annotation and the necessary static imports - pretty simple but I think its efficient. You can find the templates in this gist.

After importing the templates you can use them in a test class by typing the first letters of each template and use the content assist (Ctrl/cmd+space) to complete. This results in an assist like the one below. By pressing enter the template will be inserted into your class. Hope this makes test writing easier :)