Saturday, November 14, 2009

Categories in JUnit 4.8

This is from the tests for the upcoming JUnit 4.8 release.  It's the simplest-to-implement framework we could find for labelling tests with named categories, and running only tests with a given label.


public interface SlowTests extends CategoryType {

}

public static class A {
@Test
public void a() {
fail();
}

@Category(SlowTests.class)
@Test
public void b() {
}
}

@Category(SlowTests.class)
public static class B {
@Test
public void c() {

}
}

public static class C {
@Test
public void d() {
fail();
}
}

@RunWith(Categories.class)
@IncludeCategory(SlowTests.class)
@SuiteClasses( { A.class, B.class, C.class })
public static class SlowTestSuite {
}

3 comments:

  1. Can a single test have more than one category?

    ReplyDelete
  2. Why are the categories interfaces? I don't really like, that I have to create empty interfaces. Would it be easier to use strings? Even though this opens up the possibilites for typos.

    ReplyDelete
  3. To avoid using multiple annotations on test methods, one can use meta-annotations:

    @Target({ElementType.METHOD, ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Test
    @Category(SlowTests.class)
    public @interface SlowTest {
    }

    public static class A {
    @SlowTest
    public void a() {
    fail();
    }

    ReplyDelete