Skip to content

Commit

Permalink
Merge pull request junit-team#508 from Tibor17/junit.issues
Browse files Browse the repository at this point in the history
Improved Test: ParallelMethodTest fails few times
  • Loading branch information
David Saff committed Sep 27, 2012
2 parents 532428d + f71a2d4 commit 129a5f7
Showing 1 changed file with 31 additions and 23 deletions.
Original file line number Diff line number Diff line change
@@ -1,44 +1,52 @@
package org.junit.tests.experimental.parallel;

import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNot.not;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Test;
import org.junit.experimental.ParallelComputer;
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.Before;
import org.junit.BeforeClass;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class ParallelMethodTest {
private static final long TIMEOUT= 15;
private static volatile Thread fOne= null;
private static volatile Thread fTwo= null;

public static class Example {
private static volatile CountDownLatch fSynchronizer;

@BeforeClass public static void init() {
fSynchronizer= new CountDownLatch(2);
}
@Test public void one() throws InterruptedException {
Thread.sleep(1000);
fSynchronizer.countDown();
assertTrue(fSynchronizer.await(TIMEOUT, TimeUnit.SECONDS));
fOne= Thread.currentThread();
}
@Test public void two() throws InterruptedException {
Thread.sleep(1000);
fSynchronizer.countDown();
assertTrue(fSynchronizer.await(TIMEOUT, TimeUnit.SECONDS));
fTwo= Thread.currentThread();
}
}

@Before public void init() {
fOne= null;
fTwo= null;
}

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

private Matcher<Long> betweenInclusive(final long min, final long max) {
return new TypeSafeMatcher<Long>() {
@Override
public boolean matchesSafely(Long item) {
return item >= min && item <= max;
}

public void describeTo(Description description) {
description.appendText("between " + min + " and " + max);
}
};
assertNotNull(fOne);
assertNotNull(fTwo);
assertThat(fOne, is(not(fTwo)));
}
}

0 comments on commit 129a5f7

Please sign in to comment.