Archive for ‘Eclipse’

June 27, 2012

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
June 29, 2011

Eclipse: Running all JUnit tests at once

by Stefan

When developing test driven it is essential to be able to run all existing unit tests over and over again as fast as possible. When the application gets larger the natural way to modularize is to distribute the code among multiple projects. I am not aware of tooling that ships with Eclipse and that allows you to run all JUnit tests based on a multi-project selection or on a selected working set.

I’ve used several workarounds in the past (Ant script, TestSuites, Maven build), but none was really satisfying. I recently stumbled upon the ClassPathSuite by Johannes Link which offers exactly what I was looking for. The library internally scans the classpath for classes with JUnit4 annotated methods and then executes all found tests. Sounds simple. This classpath-based solution also has the advantage that any Eclipse classpath container can be used so this works with OSGi-based bundles as well as with Maven projects, for instance.

Setup a ClassPathSuite test project

All you need to do is to create a new project and add a single class:

import org.junit.extensions.cpsuite.ClasspathSuite;
import org.junit.runner.RunWith;

@RunWith(ClasspathSuite.class)
public class RunAllTests {
}

If you’re with Maven, the library can be referenced like this (if not follow this link):

 <repositories>
    <repository>
      <id>http://maven.xwiki.org</id>
      <url>http://maven.xwiki.org/externals</url>
    </repository>
  </repositories>
  
  <dependencies>
    <dependency>
      <groupId>cpsuite</groupId>
      <artifactId>cpsuite</artifactId>
      <version>1.2.5</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

read more »