How do you group your test cases in JUNIT / Run your test suite based on conditions or filters

If you are looking to run your @Suite annotation with some kind of parameters or you want to add filters based on which the execution can be completed. The answer is @Categories

In an agile project you want a quicker build process, therefore it is good to automate and categorize which will result in : Faster feedback. A nice way to do this is to be able to classify your tests into different categories. For example, this can make it easier to distinguish between faster running tests, and slower tests such as integration, performance, load or acceptance tests. This feature exists in TestNG, but, until recently, not in JUnit.

JUnit 4.8 introduced a new feature along these lines, called Categories

From a given set of test classes, the Categories runner runs only the classes and methods that are annotated with either the category given with the @IncludeCategory annotation, or a subtype of that category. Either classes or interfaces can be used as categories. You can also exclude categories by using the @ExcludeCategory annotation
Example:
public interface FastTests { /* category marker */ }
public interface SlowTests { /* category marker */ }

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

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

@Category({SlowTests.class, FastTests.class})
public class B {
  @Test
  public void c() {

  }
}

@RunWith(Categories.class)
@IncludeCategory(SlowTests.class)
@SuiteClasses( { A.class, B.class }) 
public class SlowTestSuite {
  // Will run A.b and B.c, but not A.a
}

@RunWith(Categories.class)
@IncludeCategory(SlowTests.class)
@ExcludeCategory(FastTests.class)
@SuiteClasses( { A.class, B.class }) 
public class SlowTestSuite {
  // Will run A.b, but not A.a or B.c
}
Happy Testing!

Comments

Popular posts from this blog

XPATH for IE / internet explorer

Website's underlying technology for automation

All time good software testing books!