Eclipse has excellent tooling support for JUnit test cases. Having code templates for JUnit test cases configured in Eclipse is a perfect addition to faster test development.
Learn to create and import JUnit 5 test templates in Eclipse.
1. JUnit 5 Test Templates
Given below template file configure three JUnit 5 template methods i.e.
setUp()
annotated with @BeforeEachtearDown()
annotated with @AfterEachtestXXX()
annotated with@Test
When we use test()
template, it automatically adds this import statement:
import static org.junit.jupiter.api.Assertions.*;
It enables the use of all static assertXXX() methods directly into the test.
<?xml version="1.0" encoding="UTF-8" standalone="no"?><templates><template autoinsert="true" context="java" deleted="false" description="JUnit5 BeforeEach" enabled="true" name="setup (JUnit5)">${:import(org.junit.jupiter.api.BeforeEach)}
@BeforeEach
public void setUp() {
${cursor}
}</template><template autoinsert="true" context="java" deleted="false" description="JUnit5 AfterEach" enabled="true" name="teardown (JUnit5)">${:import(org.junit.jupiter.api.AfterEach)}
@AfterEach
public void tearDown() {
${cursor}
}</template><template autoinsert="false" context="java-members" deleted="false" description="JUnit5 test method" enabled="true" id="org.eclipse.jdt.ui.templates.test" name="test (JUnit5)">${:import(org.junit.jupiter.api.Test)}
@Test
public void test${name}() {
${staticImport:importStatic('org.junit.jupiter.api.Assertions.*')}
${cursor}
}</template></templates>
Save this XML into a file in the preferred location. We will import this file in the next step.
2. Import Code Templates into Eclipse
- Eclipse: Window->Preferences
- Java->Editor->Templates
- Import…
- Choose file
- Verify for template names “setup (JUnit5)”, “teardown (JUnit5)” and “test (JUnit5)” specific to JUnit 5

3. How to Use Test Templates
Place the cursor in a new line and type 2-3 initials of the template method to use the template. Now hit CTRL+ENTER. It will open a pop-up in the below manner.

Choose the template method with arrow up or down keys and hit ENTER.
It will generate the template code where .you placed your cursor
Happy Learning !!
Comments