Eclipse JUnit Editor Templates

by Stefan

I recently had to set up a new Eclipse (STS) workspace and one of the first things I do is configuring some templates for JUnit Tests. Most of the tests have a skelleton like this:

import org.junit.Before;
import org.junit.Test;

public class SocialNetworkGeneratorTest {
  private SocialNetworkGenerator generator;

  @Before
  public void setUp() {
    generator = new SocialNetworkGenerator();
  }

  @Test
  public void testSth() {
    // do sth with "generator" field
  }
}

The following Eclipse Editor Template creates the setup method and stores an instance of the class under test in a field. It also handles all necessary imports.

${:import(org.junit.Before)}

  private ${type} ${name};

  @Before
  public void setUp() {
    ${name} = new ${type}();
    ${cursor}
  }

Simply assign a catchy name for the template like setup and I’m sure you will have even more fun when writing JUnit Tests.

Adding a Java Editor Template in Eclipse

For the sake of completeness the template for test cleanup:

${:import(org.junit.After)}
  @After
  public void tearDown() {
    ${cursor}
  }

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: