cgp
cgp

Reputation: 41381

Simple Method of Outputting jUnit Timings to Consumable Format

I'd like to capture the timings from my jUnit tests into some format that I can pull into excel or csv. Is there a tool or even a simple way to do this through injection to do this?

I've seen jUnitPerf, but this does not include any output, and also requires code to create sets of tests, which is far more elaborate than I am thinking.

(investigated the following questions without finding the answer)

Upvotes: 0

Views: 236

Answers (1)

NamshubWriter
NamshubWriter

Reputation: 24286

One way would be to write your own runner with a custom listener:

public class TimingRunner {

  public static void main(String... args) throws Exception {
    JUnitCore junit = new JUnitCore();
    RunListener listener = new TimingListener();
    junit.addListener(listener);

    List<Class<?>> classes = new ArrayList<Class<?>>();
    for (String each : args) {
      classes.add(Class.forName(each));
    }

    Result result = junit.run(classes.toArray(new Class[0]));
    system.exit(result.wasSuccessful() ? 0 : 1);
  }


  private static class TimingListener extends RunListener {
    private Map<Description, Long> tests = new HashMap<Description, Long>();

    @Override
    public void testStarted(Description description) {
      tests.put(description, System.currentTimeMillis());
    }

    @Override
    public void testFinished(Description description) throws Exception {
      Long startTime = tests.get(description);
      if (startTime != null) {
        long runTime = System.currentTimeMillis() - startTime.longValue();
        System.out.println(description + ", " + runtime + "\n");
      }
    }

    @Override
    public void testRunFinished(Result result) throws Exception {
      System.out.flush();
    }
  }
}

Pass the class names of the tests you want to time to TimingRunner's main.

Upvotes: 1

Related Questions