Monday, 21 September 2009

Randomly Ordered JUnit Tests

Could not be arsed to work for a bit, so got sucked into Stack Overview for a bit.
Never a good thing. Anyway one question was about how to run JUnit tests in a random order. So I sat down and looked over the APIs and gave it a bash:

import java.util.Collections;
import java.util.List;

import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.InitializationError;

/** Runs JUnit tests in a random order.
*
* @author mlk
*
*/
public class RandomBlockJUnit4ClassRunner extends BlockJUnit4ClassRunner {
   public RandomBlockJUnit4ClassRunner(Class klass)
      throws InitializationError {
      super(klass);
   }

   /** {@inheritDoc} */
   protected java.util.List computeTestMethods() {
      List methods = super.computeTestMethods();
      Collections.shuffle(methods);
      return methods;
   }

}

Annotate any class you want the unit tests to run in a random order with "@RunWith(RandomBlockJUnit4ClassRunner.class)" and hey presto randomly ordered unit tests. (Note: This required JUnit 4.5 or above).
Now JUnit does have a Sortable interface, but I've no idea how to actually ruddy use it. :'(

0 comments: