Monday, November 2, 2009

Junit hidden feature

I was surprised to see how many hidden and undocumented features Junit has. In the new release (4.7) you have access to a lot of interesting stuff (still in development for some).

Running tests in parallel (by using a scheduling strategy)


public static class Example {
@Test public void one() throws InterruptedException {
Thread.sleep(1000);
}
@Test public void two() throws InterruptedException {
Thread.sleep(1000);
}
}

@Test public void testsRunInParallel() {
long start= System.currentTimeMillis();
Result result= JUnitCore.runClasses(ParallelComputer.methods(),
Example.class);
assertTrue(result.wasSuccessful());
long end= System.currentTimeMillis();
assertThat(end - start, betweenInclusive(1000, 1500));
}


See here for more details.

Intercept test method call with @Rule


public static class HasGlobalTimeout {
public static String log;

@Rule
public MethodRule globalTimeout= new Timeout(20);

@Test
public void testInfiniteLoop1() {
log+= "ran1";
for (;;) {...}
}

@Test
public void testInfiniteLoop2() {
log+= "ran2";
for (;;) {...}
}
}


See here for more details.

0 comments:

Post a Comment