Dmytro Chyzhykov's Blog

Yet another programmer.

Eclipse JUnit 4 Code Templates

Have you already heard about Eclipse code templates?
They can really speed up writing you JUnit 4 tests and supporting staff.

For instance, modern versions of Eclipse bring us the JUnit 4 @Test code template which makes working in TDD/BDD style much easier. Eclipse JUnit 4 @Test code template
That’s awesome, isn’t it?

Unfortunately, Eclipse comes without @Before and @After, @BeforeClass and @AfterClass code templates.

Let’s write them ourselves. What do we need for that?

Firstly, open the Preferences | Java | Editor | Templates menu.
Preferences | Java | Editor | Templates

Secondly, click New button and paste one of the listed code templates listed below in the opened window
Preferences | Java | Editor | Templates | New

1
2
3
4
5
6
7
Name: Before
Description: setUp method (JUnit 4)

@Before
public void ${setUp}() throws Exception {
    ${import:import('org.junit.Before')}${cursor}
}
1
2
3
4
5
6
7
Name: Before Class
Description: setUp class method (JUnit 4)

@BeforeClass
public static void ${setUpClass}() throws Exception {
    ${import:import('org.junit.BeforeClass')}${cursor}
}
1
2
3
4
5
6
7
Name: After
Description: tearDown method (JUnit 4)

@After
public void ${tearDown}() throws Exception {
    ${import:import('org.junit.After')}${cursor}
}
1
2
3
4
5
6
7
Name: After Class
Description: tearDown class method (JUnit 4)

@AfterClass
public static void ${tearDownClass}() throws Exception {
    ${import:import('org.junit.AfterClass')}${cursor}
}

That’s all!
You can also click the Import button and load prepared templates from file.

After that you’ll be able to write these template methods much easily.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;

public class MyTest {

    @BeforeClass
    public static void setUpClass() throws Exception {

    }

    @Before
    public void setUp() throws Exception {

    }

    @After
    public void tearDown() throws Exception {

    }

    @AfterClass
    public static void tearDownClass() throws Exception {

    }

}

Read also:
- Using code templates
- Useful Eclipse Templates for Faster Coding

Updated:
- Simple JUnit4 templates for Eclipse
- Working Efficiently with JUnit in Eclipse
- Bug 395962 - [templates] JUnit templates rework