Sebastian Van Sande

Sebastian Van Sande JavaScript adventurer

IntelliJ IDEA Live Templates for Unit Testing

Introduction

When you’re doing TDD/BDD in a Java project with IntelliJ IDEA and JUnit, you really should consider using the following two Live Templates. Since I always forget how to add these templates, I decided to document it here.

The ‘setup’ Template

Adding the template

Preferences => Editor => Live Templates = click the ‘+’

Fill in “setup” as abbreviation. Enter this as template text:

@org.junit.Before
public void setUp() {
$END$
}

Define the applicable context by clicking “Define” and choosing “Java”. Click “Apply”.

Screenshot

The setup template

The ‘test’ Template

Adding the template

In the same ‘Live Templates’ screen, click the ‘+’ again Now, fill in “test” as abbreviation and enter as template text:

@org.junit.Test
public void $NAME$() {
$END$
}

Define “Java” as the applicable context again and click “OK”.

Screenshot

The test template

Verify that it works

In a (new) unit test:

  • type: setup (and press the TAB button) => a ‘setup’ method should appear
  • type: test (and press the TAB button) => a ‘test’ method should appear

EDIT

As explained by Gleighton on Reddit, this is already built in in IntelliJ:
Go to the test class and press CONTROL+ENTER (Mac) or ALT+INSERT (Linux/Windows) => here you can choose the same templates. You can edit them by pressing the right arrow key.

If you liked this post, you can share it with your followers or follow me on Twitter!

Comments

comments powered by Disqus