IntelliJ IDEA: Create JUnit Test method code snippet shortcut

I’ve been using IntelliJ over Eclipse for a while now, mainly because it feels newer and more tuned to develop with Maven-based projects. This is just me. Anyway, if you do TDD, you’ll want to take advantage of IntelliJ’s Live Templates.

In this post, I’m writing about adding JUnit test code snippets, like so:


@Test
public void testSalutationMessage() {
    System.out.println("Inside testSalutationMessage()");
    message = "Hi," + "Anton" + "!";
    assertEquals(message, util.salutationMessage());
}

You could copy-and-paste an existing method and modify it, type it manually each time, or just type “test” and hit the Tab key and, voila, it’s there! I bet you’d choose the latter…to do this in IntelliJ:

1. Go to Preferences -> Live Templates
2. Click the ‘+’ sign on the right (close to Reset)
3. Add the following:


Abbreviation: 
test

Description: 
JUnit Test Method (or whatever you like)

Template Text:
@Test
public void test$NAME$() throws Exception {
    $BODY$
}

4. Leave “Shorten FQ names” checked
5. Click on “Change” and check “Java”
6. Apply and try it out (i.e. typing “test” and hitting the Tab key should add your code snippet)

Hope this helps! Till the next. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *