views:

31

answers:

1

Does anybody know how to insert a "@RunWith anotation" above the class signature, using eclipse templates?

Ex.:

@RunWith(Parameterized.class)
public class MyClassTest {
...
    @Parameters
    public static Collection<Object[]> parameters() {
        List<Object[]> list = new ArrayList<Object[]>();
        list.add(new Object[] { "mind!", "find!" });
        list.add(new Object[] { "misunderstood", "understood" });
        return list;
    }
...
}

__

Template:

// TODO: move this '@RunWith(Parameterized.class)' to class anotation
    @Parameters
    public static Collection<Object[]> parameters() {
        ${type:elemType(collection)}<Object[]> parametersList = new ${type:elemType(collection)}<Object[]>();
        ${cursor}// TODO: populate collection
        return parametersList;
    }

__ Thanks for the help!

+1  A: 

Unfortunately, you cannot use Eclipse templates to add an annotation to an existing enclosing class (at least, not that I know of). However, there is a workaround. Here is a modified version of your template:

@${runnerType:newType(org.junit.runner.RunWith)}(${paramterizedType:newType(org.junit.runners.Parameterized)}.class)
public class ${primary_type_name} {
    @${parametersType:newType(org.junit.runners.Parameterized.Parameters)}
    public static ${collectionType:newType(java.util.Collection)}<Object[]> parameters() {
        ${baseCollectionType}<Object[]> parametersList = new ${concreteCollectionType}<Object[]>();
        ${cursor}// TODO: populate collection
        return parametersList;
    }
}

To use the template (assuming its named "Parameterized"):

  1. Create a new class in Eclipse
  2. Before doing anything else, select the stub class declaration, including the opening and closing braces.
  3. Type the name of the template, and press Cntrl+Space to activate the template (you may have to select the template from the list of templates. I only have one template called Parameterized, so Eclipse just uses it automatically for me).

The class definition will be replaced with a definition that includes the @RunWith annotation. I used the ${id:newName(reference)} template variable to cause Eclipse to automatically add all of the necessary imports (with the exception of the imports for ${baseCollectionType} and the ${concreteCollectionType}, you'll have to add those manually...thank goodness for Cntrl-Shift-M)

This is really hard to describe. You'll have to try it to see exactly how it works. Post a comment if my instructions need to be clarified.

Jim Hurne