Update concurrent tests to JUnit Jupiter

Upgrade the tests in the concurrent package to use JUnit Jupiter as
part of the effort to remove the dependency on the Vintage Engine.

While most of these changes are drop-in replacements with no functional
benefit, there are some non-obvious changes worth mentioning.

Unlike org.junit.Test, org.junit.jupiter.api.Test does not have an
"expected" argument. Instead, an explicit call to
org.junit.jupiter.api.Assertions.assertThrows is used. This call allows
the test to pinpoint the exact statement that is expected to throw the
exception and allows making the tests a bit stricter by preventing
false-positives that could occur if the setup code would throw the
expected exception instead of the statement that was supposed to throw
it.

Another notable change was performed in MemoizerTest.
JUnit Jupiter does not support JUnit 4's runners, and EasyMock has no
equivalent @Extension, so a setup method was added and the mock was
explicitly initialized.

It's also worth noting this is a minimal patch for migrating the
package's tests to Jupiter. There are several tests that can be made
made more elegant with Jupiter's new features, but that work is left
for subsequent patches.
This commit is contained in:
Allon Mureinik 2018-10-02 06:41:37 +03:00
parent 6191dedf35
commit dd761382d3
14 changed files with 350 additions and 378 deletions

View File

@ -16,12 +16,12 @@
*/ */
package org.apache.commons.lang3.concurrent; package org.apache.commons.lang3.concurrent;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* <p> * <p>
@ -42,7 +42,7 @@ public abstract class AbstractConcurrentInitializerTest {
*/ */
@Test @Test
public void testGet() throws ConcurrentException { public void testGet() throws ConcurrentException {
assertNotNull("No managed object", createInitializer().get()); assertNotNull(createInitializer().get(), "No managed object");
} }
/** /**
@ -56,7 +56,7 @@ public abstract class AbstractConcurrentInitializerTest {
final ConcurrentInitializer<Object> initializer = createInitializer(); final ConcurrentInitializer<Object> initializer = createInitializer();
final Object obj = initializer.get(); final Object obj = initializer.get();
for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
assertEquals("Got different object at " + i, obj, initializer.get()); assertEquals(obj, initializer.get(), "Got different object at " + i);
} }
} }
@ -106,7 +106,7 @@ public abstract class AbstractConcurrentInitializerTest {
// check results // check results
final Object managedObject = initializer.get(); final Object managedObject = initializer.get();
for (final GetThread t : threads) { for (final GetThread t : threads) {
assertEquals("Wrong object", managedObject, t.object); assertEquals(managedObject, t.object, "Wrong object");
} }
} }

View File

@ -16,12 +16,12 @@
*/ */
package org.apache.commons.lang3.concurrent; package org.apache.commons.lang3.concurrent;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* Test class for {@code AtomicSafeInitializer}. * Test class for {@code AtomicSafeInitializer}.
@ -31,7 +31,7 @@ public class AtomicSafeInitializerTest extends
/** The instance to be tested. */ /** The instance to be tested. */
private AtomicSafeInitializerTestImpl initializer; private AtomicSafeInitializerTestImpl initializer;
@Before @BeforeEach
public void setUp() throws Exception { public void setUp() throws Exception {
initializer = new AtomicSafeInitializerTestImpl(); initializer = new AtomicSafeInitializerTestImpl();
} }
@ -56,8 +56,7 @@ public class AtomicSafeInitializerTest extends
public void testNumberOfInitializeInvocations() throws ConcurrentException, public void testNumberOfInitializeInvocations() throws ConcurrentException,
InterruptedException { InterruptedException {
testGetConcurrent(); testGetConcurrent();
assertEquals("Wrong number of invocations", 1, assertEquals(1, initializer.initCounter.get(), "Wrong number of invocations");
initializer.initCounter.get());
} }
/** /**

View File

@ -16,15 +16,16 @@
*/ */
package org.apache.commons.lang3.concurrent; package org.apache.commons.lang3.concurrent;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.Assert.assertSame; import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
@ -42,9 +43,9 @@ public class BackgroundInitializerTest {
private void checkInitialize(final BackgroundInitializerTestImpl init) { private void checkInitialize(final BackgroundInitializerTestImpl init) {
try { try {
final Integer result = init.get(); final Integer result = init.get();
assertEquals("Wrong result", 1, result.intValue()); assertEquals(1, result.intValue(), "Wrong result");
assertEquals("Wrong number of invocations", 1, init.initializeCalls); assertEquals(1, init.initializeCalls, "Wrong number of invocations");
assertNotNull("No future", init.getFuture()); assertNotNull(init.getFuture(), "No future");
} catch (final ConcurrentException cex) { } catch (final ConcurrentException cex) {
fail("Unexpected exception: " + cex); fail("Unexpected exception: " + cex);
} }
@ -67,7 +68,7 @@ public class BackgroundInitializerTest {
@Test @Test
public void testGetActiveExecutorBeforeStart() { public void testGetActiveExecutorBeforeStart() {
final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl(); final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
assertNull("Got an executor", init.getActiveExecutor()); assertNull(init.getActiveExecutor(), "Got an executor");
} }
/** /**
@ -80,7 +81,7 @@ public class BackgroundInitializerTest {
final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl( final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl(
exec); exec);
init.start(); init.start();
assertSame("Wrong executor", exec, init.getActiveExecutor()); assertSame(exec, init.getActiveExecutor(), "Wrong executor");
checkInitialize(init); checkInitialize(init);
} finally { } finally {
exec.shutdown(); exec.shutdown();
@ -95,7 +96,7 @@ public class BackgroundInitializerTest {
public void testGetActiveExecutorTemp() { public void testGetActiveExecutorTemp() {
final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl(); final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
init.start(); init.start();
assertNotNull("No active executor", init.getActiveExecutor()); assertNotNull(init.getActiveExecutor(), "No active executor");
checkInitialize(init); checkInitialize(init);
} }
@ -106,10 +107,9 @@ public class BackgroundInitializerTest {
@Test @Test
public void testInitializeTempExecutor() { public void testInitializeTempExecutor() {
final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl(); final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
assertTrue("Wrong result of start()", init.start()); assertTrue(init.start(), "Wrong result of start()");
checkInitialize(init); checkInitialize(init);
assertTrue("Executor not shutdown", init.getActiveExecutor() assertTrue(init.getActiveExecutor().isShutdown(), "Executor not shutdown");
.isShutdown());
} }
/** /**
@ -122,12 +122,11 @@ public class BackgroundInitializerTest {
try { try {
final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl(); final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
init.setExternalExecutor(exec); init.setExternalExecutor(exec);
assertEquals("Wrong executor service", exec, init assertEquals(exec, init.getExternalExecutor(), "Wrong executor service");
.getExternalExecutor()); assertTrue(init.start(), "Wrong result of start()");
assertTrue("Wrong result of start()", init.start()); assertSame(exec, init.getActiveExecutor(), "Wrong active executor");
assertSame("Wrong active executor", exec, init.getActiveExecutor());
checkInitialize(init); checkInitialize(init);
assertFalse("Executor was shutdown", exec.isShutdown()); assertFalse(exec.isShutdown(), "Executor was shutdown");
} finally { } finally {
exec.shutdown(); exec.shutdown();
} }
@ -161,9 +160,9 @@ public class BackgroundInitializerTest {
@Test @Test
public void testStartMultipleTimes() { public void testStartMultipleTimes() {
final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl(); final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
assertTrue("Wrong result for start()", init.start()); assertTrue(init.start(), "Wrong result for start()");
for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
assertFalse("Could start again", init.start()); assertFalse(init.start(), "Could start again");
} }
checkInitialize(init); checkInitialize(init);
} }
@ -173,10 +172,10 @@ public class BackgroundInitializerTest {
* *
* @throws org.apache.commons.lang3.concurrent.ConcurrentException because the test implementation may throw it * @throws org.apache.commons.lang3.concurrent.ConcurrentException because the test implementation may throw it
*/ */
@Test(expected=IllegalStateException.class) @Test
public void testGetBeforeStart() throws ConcurrentException { public void testGetBeforeStart() throws ConcurrentException {
final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl(); final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
init.get(); assertThrows(IllegalStateException.class, init::get);
} }
/** /**
@ -193,7 +192,7 @@ public class BackgroundInitializerTest {
init.get(); init.get();
fail("Exception not thrown!"); fail("Exception not thrown!");
} catch (final Exception ex) { } catch (final Exception ex) {
assertEquals("Runtime exception not thrown", rex, ex); assertEquals(rex, ex, "Runtime exception not thrown");
} }
} }
@ -211,7 +210,7 @@ public class BackgroundInitializerTest {
init.get(); init.get();
fail("Exception not thrown!"); fail("Exception not thrown!");
} catch (final ConcurrentException cex) { } catch (final ConcurrentException cex) {
assertEquals("Exception not thrown", ex, cex.getCause()); assertEquals(ex, cex.getCause(), "Exception not thrown");
} }
} }
@ -239,7 +238,7 @@ public class BackgroundInitializerTest {
iex.set((InterruptedException) cex.getCause()); iex.set((InterruptedException) cex.getCause());
} }
} finally { } finally {
assertTrue("Thread not interrupted", isInterrupted()); assertTrue(isInterrupted(), "Thread not interrupted");
latch1.countDown(); latch1.countDown();
} }
} }
@ -249,7 +248,7 @@ public class BackgroundInitializerTest {
latch1.await(); latch1.await();
exec.shutdownNow(); exec.shutdownNow();
exec.awaitTermination(1, TimeUnit.SECONDS); exec.awaitTermination(1, TimeUnit.SECONDS);
assertNotNull("No interrupted exception", iex.get()); assertNotNull(iex.get(), "No interrupted exception");
} }
/** /**
@ -258,7 +257,7 @@ public class BackgroundInitializerTest {
@Test @Test
public void testIsStartedFalse() { public void testIsStartedFalse() {
final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl(); final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
assertFalse("Already started", init.isStarted()); assertFalse(init.isStarted(), "Already started");
} }
/** /**
@ -268,7 +267,7 @@ public class BackgroundInitializerTest {
public void testIsStartedTrue() { public void testIsStartedTrue() {
final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl(); final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
init.start(); init.start();
assertTrue("Not started", init.isStarted()); assertTrue(init.isStarted(), "Not started");
} }
/** /**
@ -279,7 +278,7 @@ public class BackgroundInitializerTest {
final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl(); final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
init.start(); init.start();
checkInitialize(init); checkInitialize(init);
assertTrue("Not started", init.isStarted()); assertTrue(init.isStarted(), "Not started");
} }
/** /**

View File

@ -16,19 +16,20 @@
*/ */
package org.apache.commons.lang3.concurrent; package org.apache.commons.lang3.concurrent;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.Assert.assertNotSame; import static org.junit.jupiter.api.Assertions.assertNotSame;
import static org.junit.Assert.assertNull; import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.Assert.assertSame; import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadFactory;
import org.easymock.EasyMock; import org.easymock.EasyMock;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* Test class for {@code BasicThreadFactory}. * Test class for {@code BasicThreadFactory}.
@ -40,7 +41,7 @@ public class BasicThreadFactoryTest {
/** The builder for creating a thread factory. */ /** The builder for creating a thread factory. */
private BasicThreadFactory.Builder builder; private BasicThreadFactory.Builder builder;
@Before @BeforeEach
public void setUp() throws Exception { public void setUp() throws Exception {
builder = new BasicThreadFactory.Builder(); builder = new BasicThreadFactory.Builder();
} }
@ -51,12 +52,11 @@ public class BasicThreadFactoryTest {
* @param factory the factory to be checked * @param factory the factory to be checked
*/ */
private void checkFactoryDefaults(final BasicThreadFactory factory) { private void checkFactoryDefaults(final BasicThreadFactory factory) {
assertNull("Got a naming pattern", factory.getNamingPattern()); assertNull(factory.getNamingPattern(), "Got a naming pattern");
assertNull("Got an exception handler", factory assertNull(factory.getUncaughtExceptionHandler(), "Got an exception handler");
.getUncaughtExceptionHandler()); assertNull(factory.getPriority(), "Got a priority");
assertNull("Got a priority", factory.getPriority()); assertNull(factory.getDaemonFlag(), "Got a daemon flag");
assertNull("Got a daemon flag", factory.getDaemonFlag()); assertNotNull(factory.getWrappedFactory(), "No wrapped factory");
assertNotNull("No wrapped factory", factory.getWrappedFactory());
} }
/** /**
@ -71,25 +71,25 @@ public class BasicThreadFactoryTest {
/** /**
* Tries to set a null naming pattern. * Tries to set a null naming pattern.
*/ */
@Test(expected = NullPointerException.class) @Test
public void testBuildNamingPatternNull() { public void testBuildNamingPatternNull() {
builder.namingPattern(null); assertThrows(NullPointerException.class, () -> builder.namingPattern(null));
} }
/** /**
* Tries to set a null wrapped factory. * Tries to set a null wrapped factory.
*/ */
@Test(expected = NullPointerException.class) @Test
public void testBuildWrappedFactoryNull() { public void testBuildWrappedFactoryNull() {
builder.wrappedFactory(null); assertThrows(NullPointerException.class, () -> builder.wrappedFactory(null));
} }
/** /**
* Tries to set a null exception handler. * Tries to set a null exception handler.
*/ */
@Test(expected = NullPointerException.class) @Test
public void testBuildUncaughtExceptionHandlerNull() { public void testBuildUncaughtExceptionHandlerNull() {
builder.uncaughtExceptionHandler(null); assertThrows(NullPointerException.class, () -> builder.uncaughtExceptionHandler(null));
} }
/** /**
@ -107,8 +107,7 @@ public class BasicThreadFactoryTest {
builder.reset(); builder.reset();
final BasicThreadFactory factory = builder.build(); final BasicThreadFactory factory = builder.build();
checkFactoryDefaults(factory); checkFactoryDefaults(factory);
assertNotSame("Wrapped factory not reset", wrappedFactory, factory assertNotSame(wrappedFactory, factory.getWrappedFactory(), "Wrapped factory not reset");
.getWrappedFactory());
EasyMock.verify(wrappedFactory, exHandler); EasyMock.verify(wrappedFactory, exHandler);
} }
@ -138,9 +137,8 @@ public class BasicThreadFactoryTest {
.namingPattern(PATTERN).build(); .namingPattern(PATTERN).build();
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
final Thread t = factory.newThread(r); final Thread t = factory.newThread(r);
assertEquals("Wrong thread name", String.format(PATTERN, Long assertEquals(String.format(PATTERN, Long.valueOf(i + 1)), t.getName(), "Wrong thread name");
.valueOf(i + 1)), t.getName()); assertEquals(i + 1, factory.getThreadCount(), "Wrong thread count");
assertEquals("Wrong thread count", i + 1, factory.getThreadCount());
} }
EasyMock.verify(wrapped, r); EasyMock.verify(wrapped, r);
} }
@ -158,8 +156,8 @@ public class BasicThreadFactoryTest {
EasyMock.expect(wrapped.newThread(r)).andReturn(t); EasyMock.expect(wrapped.newThread(r)).andReturn(t);
EasyMock.replay(wrapped, r); EasyMock.replay(wrapped, r);
final BasicThreadFactory factory = builder.wrappedFactory(wrapped).build(); final BasicThreadFactory factory = builder.wrappedFactory(wrapped).build();
assertSame("Wrong thread", t, factory.newThread(r)); assertSame(t, factory.newThread(r), "Wrong thread");
assertEquals("Name was changed", name, t.getName()); assertEquals(name, t.getName(), "Name was changed");
EasyMock.verify(wrapped, r); EasyMock.verify(wrapped, r);
} }
@ -176,8 +174,8 @@ public class BasicThreadFactoryTest {
EasyMock.replay(wrapped, r); EasyMock.replay(wrapped, r);
final BasicThreadFactory factory = builder.wrappedFactory(wrapped).daemon( final BasicThreadFactory factory = builder.wrappedFactory(wrapped).daemon(
flag).build(); flag).build();
assertSame("Wrong thread", t, factory.newThread(r)); assertSame(t, factory.newThread(r), "Wrong thread");
assertTrue("Wrong daemon flag", flag == t.isDaemon()); assertTrue(flag == t.isDaemon(), "Wrong daemon flag");
EasyMock.verify(wrapped, r); EasyMock.verify(wrapped, r);
} }
@ -213,10 +211,10 @@ public class BasicThreadFactoryTest {
EasyMock.expect(wrapped.newThread(r2)).andReturn(t2); EasyMock.expect(wrapped.newThread(r2)).andReturn(t2);
EasyMock.replay(wrapped, r1, r2); EasyMock.replay(wrapped, r1, r2);
final BasicThreadFactory factory = builder.wrappedFactory(wrapped).build(); final BasicThreadFactory factory = builder.wrappedFactory(wrapped).build();
assertSame("Wrong thread 1", t1, factory.newThread(r1)); assertSame(t1, factory.newThread(r1), "Wrong thread 1");
assertTrue("No daemon thread", t1.isDaemon()); assertTrue(t1.isDaemon(), "No daemon thread");
assertSame("Wrong thread 2", t2, factory.newThread(r2)); assertSame(t2, factory.newThread(r2), "Wrong thread 2");
assertFalse("A daemon thread", t2.isDaemon()); assertFalse(t2.isDaemon(), "A daemon thread");
EasyMock.verify(wrapped, r1, r2); EasyMock.verify(wrapped, r1, r2);
} }
@ -233,8 +231,8 @@ public class BasicThreadFactoryTest {
final int priority = Thread.NORM_PRIORITY + 1; final int priority = Thread.NORM_PRIORITY + 1;
final BasicThreadFactory factory = builder.wrappedFactory(wrapped).priority( final BasicThreadFactory factory = builder.wrappedFactory(wrapped).priority(
priority).build(); priority).build();
assertSame("Wrong thread", t, factory.newThread(r)); assertSame(t, factory.newThread(r), "Wrong thread");
assertEquals("Wrong priority", priority, t.getPriority()); assertEquals(priority, t.getPriority(), "Wrong priority");
EasyMock.verify(wrapped, r); EasyMock.verify(wrapped, r);
} }
@ -252,8 +250,8 @@ public class BasicThreadFactoryTest {
EasyMock.expect(wrapped.newThread(r)).andReturn(t); EasyMock.expect(wrapped.newThread(r)).andReturn(t);
EasyMock.replay(wrapped, r); EasyMock.replay(wrapped, r);
final BasicThreadFactory factory = builder.wrappedFactory(wrapped).build(); final BasicThreadFactory factory = builder.wrappedFactory(wrapped).build();
assertSame("Wrong thread", t, factory.newThread(r)); assertSame(t, factory.newThread(r), "Wrong thread");
assertEquals("Wrong priority", orgPriority, t.getPriority()); assertEquals(orgPriority, t.getPriority(), "Wrong priority");
EasyMock.verify(wrapped, r); EasyMock.verify(wrapped, r);
} }
@ -271,9 +269,8 @@ public class BasicThreadFactoryTest {
EasyMock.replay(wrapped, r, handler); EasyMock.replay(wrapped, r, handler);
final BasicThreadFactory factory = builder.wrappedFactory(wrapped) final BasicThreadFactory factory = builder.wrappedFactory(wrapped)
.uncaughtExceptionHandler(handler).build(); .uncaughtExceptionHandler(handler).build();
assertSame("Wrong thread", t, factory.newThread(r)); assertSame(t, factory.newThread(r), "Wrong thread");
assertEquals("Wrong exception handler", handler, t assertEquals(handler, t.getUncaughtExceptionHandler(), "Wrong exception handler");
.getUncaughtExceptionHandler());
EasyMock.verify(wrapped, r, handler); EasyMock.verify(wrapped, r, handler);
} }
@ -292,9 +289,8 @@ public class BasicThreadFactoryTest {
EasyMock.expect(wrapped.newThread(r)).andReturn(t); EasyMock.expect(wrapped.newThread(r)).andReturn(t);
EasyMock.replay(wrapped, r, handler); EasyMock.replay(wrapped, r, handler);
final BasicThreadFactory factory = builder.wrappedFactory(wrapped).build(); final BasicThreadFactory factory = builder.wrappedFactory(wrapped).build();
assertSame("Wrong thread", t, factory.newThread(r)); assertSame(t, factory.newThread(r), "Wrong thread");
assertEquals("Wrong exception handler", handler, t assertEquals(handler, t.getUncaughtExceptionHandler(), "Wrong exception handler");
.getUncaughtExceptionHandler());
EasyMock.verify(wrapped, r, handler); EasyMock.verify(wrapped, r, handler);
} }
} }

View File

@ -16,14 +16,15 @@
*/ */
package org.apache.commons.lang3.concurrent; package org.apache.commons.lang3.concurrent;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* Test class for {@code CallableBackgroundInitializer} * Test class for {@code CallableBackgroundInitializer}
@ -36,9 +37,9 @@ public class CallableBackgroundInitializerTest {
* Tries to create an instance without a Callable. This should cause an * Tries to create an instance without a Callable. This should cause an
* exception. * exception.
*/ */
@Test(expected=IllegalArgumentException.class) @Test()
public void testInitNullCallable() { public void testInitNullCallable() {
new CallableBackgroundInitializer<>(null); assertThrows(IllegalArgumentException.class, () -> new CallableBackgroundInitializer<>(null));
} }
/** /**
@ -50,7 +51,7 @@ public class CallableBackgroundInitializerTest {
final ExecutorService exec = Executors.newSingleThreadExecutor(); final ExecutorService exec = Executors.newSingleThreadExecutor();
final CallableBackgroundInitializer<Integer> init = new CallableBackgroundInitializer<>( final CallableBackgroundInitializer<Integer> init = new CallableBackgroundInitializer<>(
new TestCallable(), exec); new TestCallable(), exec);
assertEquals("Executor not set", exec, init.getExternalExecutor()); assertEquals(exec, init.getExternalExecutor(), "Executor not set");
exec.shutdown(); exec.shutdown();
exec.awaitTermination(1, TimeUnit.SECONDS); exec.awaitTermination(1, TimeUnit.SECONDS);
} }
@ -59,11 +60,11 @@ public class CallableBackgroundInitializerTest {
* Tries to pass a null Callable to the constructor that takes an executor. * Tries to pass a null Callable to the constructor that takes an executor.
* This should cause an exception. * This should cause an exception.
*/ */
@Test(expected=IllegalArgumentException.class) @Test
public void testInitExecutorNullCallable() throws InterruptedException { public void testInitExecutorNullCallable() throws InterruptedException {
final ExecutorService exec = Executors.newSingleThreadExecutor(); final ExecutorService exec = Executors.newSingleThreadExecutor();
try { try {
new CallableBackgroundInitializer<Integer>(null, exec); assertThrows(IllegalArgumentException.class, () -> new CallableBackgroundInitializer<Integer>(null, exec));
} finally { } finally {
exec.shutdown(); exec.shutdown();
exec.awaitTermination(1, TimeUnit.SECONDS); exec.awaitTermination(1, TimeUnit.SECONDS);
@ -81,8 +82,8 @@ public class CallableBackgroundInitializerTest {
final TestCallable call = new TestCallable(); final TestCallable call = new TestCallable();
final CallableBackgroundInitializer<Integer> init = new CallableBackgroundInitializer<>( final CallableBackgroundInitializer<Integer> init = new CallableBackgroundInitializer<>(
call); call);
assertEquals("Wrong result", RESULT, init.initialize()); assertEquals(RESULT, init.initialize(), "Wrong result");
assertEquals("Wrong number of invocations", 1, call.callCount); assertEquals(1, call.callCount, "Wrong number of invocations");
} }
/** /**

View File

@ -17,11 +17,12 @@
package org.apache.commons.lang3.concurrent; package org.apache.commons.lang3.concurrent;
import org.apache.commons.lang3.exception.AbstractExceptionTest; import org.apache.commons.lang3.exception.AbstractExceptionTest;
import org.junit.Test; import org.junit.jupiter.api.Test;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.Assert.assertNull; import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
/** /**
@ -29,42 +30,50 @@ import static org.junit.Assert.assertNull;
*/ */
public class CircuitBreakingExceptionTest extends AbstractExceptionTest { public class CircuitBreakingExceptionTest extends AbstractExceptionTest {
@Test(expected = CircuitBreakingException.class) @Test
public void testThrowingInformativeException() throws Exception { public void testThrowingInformativeException() {
assertThrows(CircuitBreakingException.class, () -> {
throw new CircuitBreakingException(EXCEPTION_MESSAGE, generateCause()); throw new CircuitBreakingException(EXCEPTION_MESSAGE, generateCause());
});
} }
@Test(expected = CircuitBreakingException.class) @Test
public void testThrowingExceptionWithMessage() throws Exception { public void testThrowingExceptionWithMessage() {
assertThrows(CircuitBreakingException.class, () -> {
throw new CircuitBreakingException(EXCEPTION_MESSAGE); throw new CircuitBreakingException(EXCEPTION_MESSAGE);
});
} }
@Test(expected = CircuitBreakingException.class) @Test
public void testThrowingExceptionWithCause() throws Exception { public void testThrowingExceptionWithCause() {
assertThrows(CircuitBreakingException.class, () -> {
throw new CircuitBreakingException(generateCause()); throw new CircuitBreakingException(generateCause());
});
} }
@Test(expected = CircuitBreakingException.class) @Test
public void testThrowingEmptyException() throws Exception { public void testThrowingEmptyException() {
assertThrows(CircuitBreakingException.class, () -> {
throw new CircuitBreakingException(); throw new CircuitBreakingException();
});
} }
@Test @Test
public void testWithCauseAndMessage() throws Exception { public void testWithCauseAndMessage() throws Exception {
final Exception exception = new CircuitBreakingException(EXCEPTION_MESSAGE, generateCause()); final Exception exception = new CircuitBreakingException(EXCEPTION_MESSAGE, generateCause());
assertNotNull(exception); assertNotNull(exception);
assertEquals(WRONG_EXCEPTION_MESSAGE, EXCEPTION_MESSAGE, exception.getMessage()); assertEquals(EXCEPTION_MESSAGE, exception.getMessage(), WRONG_EXCEPTION_MESSAGE);
final Throwable cause = exception.getCause(); final Throwable cause = exception.getCause();
assertNotNull(cause); assertNotNull(cause);
assertEquals(WRONG_CAUSE_MESSAGE, CAUSE_MESSAGE, cause.getMessage()); assertEquals(CAUSE_MESSAGE, cause.getMessage(), WRONG_CAUSE_MESSAGE);
} }
@Test @Test
public void testWithoutCause() throws Exception { public void testWithoutCause() throws Exception {
final Exception exception = new CircuitBreakingException(EXCEPTION_MESSAGE); final Exception exception = new CircuitBreakingException(EXCEPTION_MESSAGE);
assertNotNull(exception); assertNotNull(exception);
assertEquals(WRONG_EXCEPTION_MESSAGE, EXCEPTION_MESSAGE, exception.getMessage()); assertEquals(EXCEPTION_MESSAGE, exception.getMessage(), WRONG_EXCEPTION_MESSAGE);
final Throwable cause = exception.getCause(); final Throwable cause = exception.getCause();
assertNull(cause); assertNull(cause);
@ -78,6 +87,6 @@ public class CircuitBreakingExceptionTest extends AbstractExceptionTest {
final Throwable cause = exception.getCause(); final Throwable cause = exception.getCause();
assertNotNull(cause); assertNotNull(cause);
assertEquals(WRONG_CAUSE_MESSAGE, CAUSE_MESSAGE, cause.getMessage()); assertEquals(CAUSE_MESSAGE, cause.getMessage(), WRONG_CAUSE_MESSAGE);
} }
} }

View File

@ -16,13 +16,14 @@
*/ */
package org.apache.commons.lang3.concurrent; package org.apache.commons.lang3.concurrent;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.Assert.assertNull; import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.Assert.assertSame; import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ConcurrentMap;
@ -31,7 +32,7 @@ import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.easymock.EasyMock; import org.easymock.EasyMock;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* Test class for {@link ConcurrentUtils}. * Test class for {@link ConcurrentUtils}.
@ -40,49 +41,49 @@ public class ConcurrentUtilsTest {
/** /**
* Tests creating a ConcurrentException with a runtime exception as cause. * Tests creating a ConcurrentException with a runtime exception as cause.
*/ */
@Test(expected = IllegalArgumentException.class) @Test
public void testConcurrentExceptionCauseUnchecked() { public void testConcurrentExceptionCauseUnchecked() {
new ConcurrentException(new RuntimeException()); assertThrows(IllegalArgumentException.class, () -> new ConcurrentException(new RuntimeException()));
} }
/** /**
* Tests creating a ConcurrentException with an error as cause. * Tests creating a ConcurrentException with an error as cause.
*/ */
@Test(expected = IllegalArgumentException.class) @Test
public void testConcurrentExceptionCauseError() { public void testConcurrentExceptionCauseError() {
new ConcurrentException("An error", new Error()); assertThrows(IllegalArgumentException.class, () -> new ConcurrentException("An error", new Error()));
} }
/** /**
* Tests creating a ConcurrentException with null as cause. * Tests creating a ConcurrentException with null as cause.
*/ */
@Test(expected = IllegalArgumentException.class) @Test
public void testConcurrentExceptionCauseNull() { public void testConcurrentExceptionCauseNull() {
new ConcurrentException(null); assertThrows(IllegalArgumentException.class, () -> new ConcurrentException(null));
} }
/** /**
* Tries to create a ConcurrentRuntimeException with a runtime as cause. * Tries to create a ConcurrentRuntimeException with a runtime as cause.
*/ */
@Test(expected = IllegalArgumentException.class) @Test
public void testConcurrentRuntimeExceptionCauseUnchecked() { public void testConcurrentRuntimeExceptionCauseUnchecked() {
new ConcurrentRuntimeException(new RuntimeException()); assertThrows(IllegalArgumentException.class, () -> new ConcurrentRuntimeException(new RuntimeException()));
} }
/** /**
* Tries to create a ConcurrentRuntimeException with an error as cause. * Tries to create a ConcurrentRuntimeException with an error as cause.
*/ */
@Test(expected = IllegalArgumentException.class) @Test
public void testConcurrentRuntimeExceptionCauseError() { public void testConcurrentRuntimeExceptionCauseError() {
new ConcurrentRuntimeException("An error", new Error()); assertThrows(IllegalArgumentException.class, () -> new ConcurrentRuntimeException("An error", new Error()));
} }
/** /**
* Tries to create a ConcurrentRuntimeException with null as cause. * Tries to create a ConcurrentRuntimeException with null as cause.
*/ */
@Test(expected = IllegalArgumentException.class) @Test
public void testConcurrentRuntimeExceptionCauseNull() { public void testConcurrentRuntimeExceptionCauseNull() {
new ConcurrentRuntimeException(null); assertThrows(IllegalArgumentException.class, () -> new ConcurrentRuntimeException(null));
} }
/** /**
@ -90,7 +91,7 @@ public class ConcurrentUtilsTest {
*/ */
@Test @Test
public void testExtractCauseNull() { public void testExtractCauseNull() {
assertNull("Non null result", ConcurrentUtils.extractCause(null)); assertNull(ConcurrentUtils.extractCause(null), "Non null result");
} }
/** /**
@ -98,8 +99,7 @@ public class ConcurrentUtilsTest {
*/ */
@Test @Test
public void testExtractCauseNullCause() { public void testExtractCauseNullCause() {
assertNull("Non null result", ConcurrentUtils assertNull(ConcurrentUtils.extractCause(new ExecutionException("Test", null)), "Non null result");
.extractCause(new ExecutionException("Test", null)));
} }
/** /**
@ -112,7 +112,7 @@ public class ConcurrentUtilsTest {
ConcurrentUtils.extractCause(new ExecutionException(err)); ConcurrentUtils.extractCause(new ExecutionException(err));
fail("Error not thrown!"); fail("Error not thrown!");
} catch (final Error e) { } catch (final Error e) {
assertEquals("Wrong error", err, e); assertEquals(err, e, "Wrong error");
} }
} }
@ -126,7 +126,7 @@ public class ConcurrentUtilsTest {
ConcurrentUtils.extractCause(new ExecutionException(rex)); ConcurrentUtils.extractCause(new ExecutionException(rex));
fail("Runtime exception not thrown!"); fail("Runtime exception not thrown!");
} catch (final RuntimeException r) { } catch (final RuntimeException r) {
assertEquals("Wrong exception", rex, r); assertEquals(rex, r, "Wrong exception");
} }
} }
@ -138,7 +138,7 @@ public class ConcurrentUtilsTest {
final Exception ex = new Exception("Test"); final Exception ex = new Exception("Test");
final ConcurrentException cex = ConcurrentUtils final ConcurrentException cex = ConcurrentUtils
.extractCause(new ExecutionException(ex)); .extractCause(new ExecutionException(ex));
assertSame("Wrong cause", ex, cex.getCause()); assertSame(ex, cex.getCause(), "Wrong cause");
} }
/** /**
@ -146,7 +146,7 @@ public class ConcurrentUtilsTest {
*/ */
@Test @Test
public void testExtractCauseUncheckedNull() { public void testExtractCauseUncheckedNull() {
assertNull("Non null result", ConcurrentUtils.extractCauseUnchecked(null)); assertNull(ConcurrentUtils.extractCauseUnchecked(null), "Non null result");
} }
/** /**
@ -154,8 +154,7 @@ public class ConcurrentUtilsTest {
*/ */
@Test @Test
public void testExtractCauseUncheckedNullCause() { public void testExtractCauseUncheckedNullCause() {
assertNull("Non null result", ConcurrentUtils assertNull(ConcurrentUtils.extractCauseUnchecked(new ExecutionException("Test", null)), "Non null result");
.extractCauseUnchecked(new ExecutionException("Test", null)));
} }
/** /**
@ -168,7 +167,7 @@ public class ConcurrentUtilsTest {
ConcurrentUtils.extractCauseUnchecked(new ExecutionException(err)); ConcurrentUtils.extractCauseUnchecked(new ExecutionException(err));
fail("Error not thrown!"); fail("Error not thrown!");
} catch (final Error e) { } catch (final Error e) {
assertEquals("Wrong error", err, e); assertEquals(err, e, "Wrong error");
} }
} }
@ -182,7 +181,7 @@ public class ConcurrentUtilsTest {
ConcurrentUtils.extractCauseUnchecked(new ExecutionException(rex)); ConcurrentUtils.extractCauseUnchecked(new ExecutionException(rex));
fail("Runtime exception not thrown!"); fail("Runtime exception not thrown!");
} catch (final RuntimeException r) { } catch (final RuntimeException r) {
assertEquals("Wrong exception", rex, r); assertEquals(rex, r, "Wrong exception");
} }
} }
@ -194,7 +193,7 @@ public class ConcurrentUtilsTest {
final Exception ex = new Exception("Test"); final Exception ex = new Exception("Test");
final ConcurrentRuntimeException cex = ConcurrentUtils final ConcurrentRuntimeException cex = ConcurrentUtils
.extractCauseUnchecked(new ExecutionException(ex)); .extractCauseUnchecked(new ExecutionException(ex));
assertSame("Wrong cause", ex, cex.getCause()); assertSame(ex, cex.getCause(), "Wrong cause");
} }
/** /**
@ -209,7 +208,7 @@ public class ConcurrentUtilsTest {
ConcurrentUtils.handleCause(new ExecutionException(err)); ConcurrentUtils.handleCause(new ExecutionException(err));
fail("Error not thrown!"); fail("Error not thrown!");
} catch (final Error e) { } catch (final Error e) {
assertEquals("Wrong error", err, e); assertEquals(err, e, "Wrong error");
} }
} }
@ -225,7 +224,7 @@ public class ConcurrentUtilsTest {
ConcurrentUtils.handleCause(new ExecutionException(rex)); ConcurrentUtils.handleCause(new ExecutionException(rex));
fail("Runtime exception not thrown!"); fail("Runtime exception not thrown!");
} catch (final RuntimeException r) { } catch (final RuntimeException r) {
assertEquals("Wrong exception", rex, r); assertEquals(rex, r, "Wrong exception");
} }
} }
@ -239,7 +238,7 @@ public class ConcurrentUtilsTest {
ConcurrentUtils.handleCause(new ExecutionException(ex)); ConcurrentUtils.handleCause(new ExecutionException(ex));
fail("ConcurrentException not thrown!"); fail("ConcurrentException not thrown!");
} catch (final ConcurrentException cex) { } catch (final ConcurrentException cex) {
assertEquals("Wrong cause", ex, cex.getCause()); assertEquals(ex, cex.getCause(), "Wrong cause");
} }
} }
@ -266,7 +265,7 @@ public class ConcurrentUtilsTest {
ConcurrentUtils.handleCauseUnchecked(new ExecutionException(err)); ConcurrentUtils.handleCauseUnchecked(new ExecutionException(err));
fail("Error not thrown!"); fail("Error not thrown!");
} catch (final Error e) { } catch (final Error e) {
assertEquals("Wrong error", err, e); assertEquals(err, e, "Wrong error");
} }
} }
@ -280,7 +279,7 @@ public class ConcurrentUtilsTest {
ConcurrentUtils.handleCauseUnchecked(new ExecutionException(rex)); ConcurrentUtils.handleCauseUnchecked(new ExecutionException(rex));
fail("Runtime exception not thrown!"); fail("Runtime exception not thrown!");
} catch (final RuntimeException r) { } catch (final RuntimeException r) {
assertEquals("Wrong exception", rex, r); assertEquals(rex, r, "Wrong exception");
} }
} }
@ -294,7 +293,7 @@ public class ConcurrentUtilsTest {
ConcurrentUtils.handleCauseUnchecked(new ExecutionException(ex)); ConcurrentUtils.handleCauseUnchecked(new ExecutionException(ex));
fail("ConcurrentRuntimeException not thrown!"); fail("ConcurrentRuntimeException not thrown!");
} catch (final ConcurrentRuntimeException crex) { } catch (final ConcurrentRuntimeException crex) {
assertEquals("Wrong cause", ex, crex.getCause()); assertEquals(ex, crex.getCause(), "Wrong cause");
} }
} }
@ -318,7 +317,7 @@ public class ConcurrentUtilsTest {
*/ */
@Test @Test
public void testInitializeNull() throws ConcurrentException { public void testInitializeNull() throws ConcurrentException {
assertNull("Got a result", ConcurrentUtils.initialize(null)); assertNull(ConcurrentUtils.initialize(null), "Got a result");
} }
/** /**
@ -335,8 +334,7 @@ public class ConcurrentUtilsTest {
final Object result = new Object(); final Object result = new Object();
EasyMock.expect(init.get()).andReturn(result); EasyMock.expect(init.get()).andReturn(result);
EasyMock.replay(init); EasyMock.replay(init);
assertSame("Wrong result object", result, ConcurrentUtils assertSame(result, ConcurrentUtils.initialize(init), "Wrong result object");
.initialize(init));
EasyMock.verify(init); EasyMock.verify(init);
} }
@ -345,7 +343,7 @@ public class ConcurrentUtilsTest {
*/ */
@Test @Test
public void testInitializeUncheckedNull() { public void testInitializeUncheckedNull() {
assertNull("Got a result", ConcurrentUtils.initializeUnchecked(null)); assertNull(ConcurrentUtils.initializeUnchecked(null), "Got a result");
} }
/** /**
@ -353,7 +351,7 @@ public class ConcurrentUtilsTest {
*/ */
@Test @Test
public void testUninitializedConcurrentRuntimeException() { public void testUninitializedConcurrentRuntimeException() {
assertNotNull("Error creating empty ConcurrentRuntimeException", new ConcurrentRuntimeException()); assertNotNull(new ConcurrentRuntimeException(), "Error creating empty ConcurrentRuntimeException");
} }
/** /**
@ -370,8 +368,7 @@ public class ConcurrentUtilsTest {
final Object result = new Object(); final Object result = new Object();
EasyMock.expect(init.get()).andReturn(result); EasyMock.expect(init.get()).andReturn(result);
EasyMock.replay(init); EasyMock.replay(init);
assertSame("Wrong result object", result, ConcurrentUtils assertSame(result, ConcurrentUtils.initializeUnchecked(init), "Wrong result object");
.initializeUnchecked(init));
EasyMock.verify(init); EasyMock.verify(init);
} }
@ -393,7 +390,7 @@ public class ConcurrentUtilsTest {
ConcurrentUtils.initializeUnchecked(init); ConcurrentUtils.initializeUnchecked(init);
fail("Exception not thrown!"); fail("Exception not thrown!");
} catch (final ConcurrentRuntimeException crex) { } catch (final ConcurrentRuntimeException crex) {
assertSame("Wrong cause", cause, crex.getCause()); assertSame(cause, crex.getCause(), "Wrong cause");
} }
EasyMock.verify(init); EasyMock.verify(init);
} }
@ -445,9 +442,8 @@ public class ConcurrentUtilsTest {
final Integer value = 42; final Integer value = 42;
final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<>(); final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<>();
map.put(key, value); map.put(key, value);
assertEquals("Wrong result", value, assertEquals(value, ConcurrentUtils.putIfAbsent(map, key, 0), "Wrong result");
ConcurrentUtils.putIfAbsent(map, key, 0)); assertEquals(value, map.get(key), "Wrong value in map");
assertEquals("Wrong value in map", value, map.get(key));
} }
/** /**
@ -458,9 +454,8 @@ public class ConcurrentUtilsTest {
final String key = "testKey"; final String key = "testKey";
final Integer value = 42; final Integer value = 42;
final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<>(); final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<>();
assertEquals("Wrong result", value, assertEquals(value, ConcurrentUtils.putIfAbsent(map, key, value), "Wrong result");
ConcurrentUtils.putIfAbsent(map, key, value)); assertEquals(value, map.get(key), "Wrong value in map");
assertEquals("Wrong value in map", value, map.get(key));
} }
/** /**
@ -468,8 +463,7 @@ public class ConcurrentUtilsTest {
*/ */
@Test @Test
public void testPutIfAbsentNullMap() { public void testPutIfAbsentNullMap() {
assertNull("Wrong result", assertNull(ConcurrentUtils.putIfAbsent(null, "test", 100), "Wrong result");
ConcurrentUtils.putIfAbsent(null, "test", 100));
} }
/** /**
@ -488,9 +482,8 @@ public class ConcurrentUtilsTest {
final Integer value = 42; final Integer value = 42;
final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<>(); final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<>();
map.put(key, value); map.put(key, value);
assertEquals("Wrong result", value, assertEquals(value, ConcurrentUtils.createIfAbsent(map, key, init), "Wrong result");
ConcurrentUtils.createIfAbsent(map, key, init)); assertEquals(value, map.get(key), "Wrong value in map");
assertEquals("Wrong value in map", value, map.get(key));
EasyMock.verify(init); EasyMock.verify(init);
} }
@ -510,9 +503,8 @@ public class ConcurrentUtilsTest {
EasyMock.expect(init.get()).andReturn(value); EasyMock.expect(init.get()).andReturn(value);
EasyMock.replay(init); EasyMock.replay(init);
final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<>(); final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<>();
assertEquals("Wrong result", value, assertEquals(value, ConcurrentUtils.createIfAbsent(map, key, init), "Wrong result");
ConcurrentUtils.createIfAbsent(map, key, init)); assertEquals(value, map.get(key), "Wrong value in map");
assertEquals("Wrong value in map", value, map.get(key));
EasyMock.verify(init); EasyMock.verify(init);
} }
@ -528,8 +520,7 @@ public class ConcurrentUtilsTest {
ConcurrentInitializer<Integer> init = EasyMock ConcurrentInitializer<Integer> init = EasyMock
.createMock(ConcurrentInitializer.class); .createMock(ConcurrentInitializer.class);
EasyMock.replay(init); EasyMock.replay(init);
assertNull("Wrong result", assertNull(ConcurrentUtils.createIfAbsent(null, "test", init), "Wrong result");
ConcurrentUtils.createIfAbsent(null, "test", init));
EasyMock.verify(init); EasyMock.verify(init);
} }
@ -544,9 +535,8 @@ public class ConcurrentUtilsTest {
final String key = "testKey"; final String key = "testKey";
final Integer value = 42; final Integer value = 42;
map.put(key, value); map.put(key, value);
assertNull("Wrong result", assertNull(ConcurrentUtils.createIfAbsent(map, key, null), "Wrong result");
ConcurrentUtils.createIfAbsent(map, key, null)); assertEquals(value, map.get(key), "Map was changed");
assertEquals("Map was changed", value, map.get(key));
} }
/** /**
@ -557,10 +547,9 @@ public class ConcurrentUtilsTest {
final String key = "testKey"; final String key = "testKey";
final Integer value = 42; final Integer value = 42;
final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<>(); final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<>();
assertEquals("Wrong result", value, assertEquals(value, ConcurrentUtils.createIfAbsentUnchecked(map, key, new ConstantInitializer<>(value)),
ConcurrentUtils.createIfAbsentUnchecked(map, key, "Wrong result");
new ConstantInitializer<>(value))); assertEquals(value, map.get(key), "Wrong value in map");
assertEquals("Wrong value in map", value, map.get(key));
} }
/** /**
@ -583,7 +572,7 @@ public class ConcurrentUtilsTest {
new ConcurrentHashMap<>(), "test", init); new ConcurrentHashMap<>(), "test", init);
fail("Exception not thrown!"); fail("Exception not thrown!");
} catch (final ConcurrentRuntimeException crex) { } catch (final ConcurrentRuntimeException crex) {
assertEquals("Wrong cause", ex, crex.getCause()); assertEquals(ex, crex.getCause(), "Wrong cause");
} }
EasyMock.verify(init); EasyMock.verify(init);
} }

View File

@ -16,13 +16,13 @@
*/ */
package org.apache.commons.lang3.concurrent; package org.apache.commons.lang3.concurrent;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.regex.Pattern; import java.util.regex.Pattern;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* Test class for {@code ConstantInitializer}. * Test class for {@code ConstantInitializer}.
@ -34,7 +34,7 @@ public class ConstantInitializerTest {
/** The initializer to be tested. */ /** The initializer to be tested. */
private ConstantInitializer<Integer> init; private ConstantInitializer<Integer> init;
@Before @BeforeEach
public void setUp() throws Exception { public void setUp() throws Exception {
init = new ConstantInitializer<>(VALUE); init = new ConstantInitializer<>(VALUE);
} }
@ -46,12 +46,11 @@ public class ConstantInitializerTest {
* @param expected the expected result * @param expected the expected result
*/ */
private void checkEquals(final Object obj, final boolean expected) { private void checkEquals(final Object obj, final boolean expected) {
assertTrue("Wrong result of equals", expected == init.equals(obj)); assertTrue(expected == init.equals(obj), "Wrong result of equals");
if (obj != null) { if (obj != null) {
assertTrue("Not symmetric", expected == obj.equals(init)); assertTrue(expected == obj.equals(init), "Not symmetric");
if (expected) { if (expected) {
assertEquals("Different hash codes", init.hashCode(), assertEquals(init.hashCode(), obj.hashCode(), "Different hash codes");
obj.hashCode());
} }
} }
} }
@ -61,7 +60,7 @@ public class ConstantInitializerTest {
*/ */
@Test @Test
public void testGetObject() { public void testGetObject() {
assertEquals("Wrong object", VALUE, init.getObject()); assertEquals(VALUE, init.getObject(), "Wrong object");
} }
/** /**
@ -71,7 +70,7 @@ public class ConstantInitializerTest {
*/ */
@Test @Test
public void testGet() throws ConcurrentException { public void testGet() throws ConcurrentException {
assertEquals("Wrong object", VALUE, init.get()); assertEquals(VALUE, init.get(), "Wrong object");
} }
/** /**
@ -119,7 +118,7 @@ public class ConstantInitializerTest {
final Pattern pattern = Pattern final Pattern pattern = Pattern
.compile("ConstantInitializer@-?\\d+ \\[ object = " + VALUE .compile("ConstantInitializer@-?\\d+ \\[ object = " + VALUE
+ " \\]"); + " \\]");
assertTrue("Wrong string: " + s, pattern.matcher(s).matches()); assertTrue(pattern.matcher(s).matches(), "Wrong string: " + s);
} }
/** /**
@ -128,6 +127,6 @@ public class ConstantInitializerTest {
@Test @Test
public void testToStringNull() { public void testToStringNull() {
final String s = new ConstantInitializer<>(null).toString(); final String s = new ConstantInitializer<>(null).toString();
assertTrue("Object not found: " + s, s.indexOf("object = null") > 0); assertTrue(s.indexOf("object = null") > 0, "Object not found: " + s);
} }
} }

View File

@ -16,11 +16,11 @@
*/ */
package org.apache.commons.lang3.concurrent; package org.apache.commons.lang3.concurrent;
import static org.junit.Assert.assertArrayEquals; import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.Assert.assertNotEquals; import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener; import java.beans.PropertyChangeListener;
@ -29,7 +29,7 @@ import java.util.List;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* Test class for {@code EventCountCircuitBreaker}. * Test class for {@code EventCountCircuitBreaker}.
@ -51,9 +51,8 @@ public class EventCountCircuitBreakerTest {
public void testIntervalCalculation() { public void testIntervalCalculation() {
final EventCountCircuitBreaker breaker = new EventCountCircuitBreaker(OPENING_THRESHOLD, 1, final EventCountCircuitBreaker breaker = new EventCountCircuitBreaker(OPENING_THRESHOLD, 1,
TimeUnit.SECONDS, CLOSING_THRESHOLD, 2, TimeUnit.MILLISECONDS); TimeUnit.SECONDS, CLOSING_THRESHOLD, 2, TimeUnit.MILLISECONDS);
assertEquals("Wrong opening interval", NANO_FACTOR, breaker.getOpeningInterval()); assertEquals(NANO_FACTOR, breaker.getOpeningInterval(), "Wrong opening interval");
assertEquals("Wrong closing interval", 2 * NANO_FACTOR / 1000, assertEquals(2 * NANO_FACTOR / 1000, breaker.getClosingInterval(), "Wrong closing interval");
breaker.getClosingInterval());
} }
/** /**
@ -64,7 +63,7 @@ public class EventCountCircuitBreakerTest {
public void testDefaultClosingInterval() { public void testDefaultClosingInterval() {
final EventCountCircuitBreaker breaker = new EventCountCircuitBreaker(OPENING_THRESHOLD, 1, final EventCountCircuitBreaker breaker = new EventCountCircuitBreaker(OPENING_THRESHOLD, 1,
TimeUnit.SECONDS, CLOSING_THRESHOLD); TimeUnit.SECONDS, CLOSING_THRESHOLD);
assertEquals("Wrong closing interval", NANO_FACTOR, breaker.getClosingInterval()); assertEquals(NANO_FACTOR, breaker.getClosingInterval(), "Wrong closing interval");
} }
/** /**
@ -75,9 +74,8 @@ public class EventCountCircuitBreakerTest {
public void testDefaultClosingThreshold() { public void testDefaultClosingThreshold() {
final EventCountCircuitBreaker breaker = new EventCountCircuitBreaker(OPENING_THRESHOLD, 1, final EventCountCircuitBreaker breaker = new EventCountCircuitBreaker(OPENING_THRESHOLD, 1,
TimeUnit.SECONDS); TimeUnit.SECONDS);
assertEquals("Wrong closing interval", NANO_FACTOR, breaker.getClosingInterval()); assertEquals(NANO_FACTOR, breaker.getClosingInterval(), "Wrong closing interval");
assertEquals("Wrong closing threshold", OPENING_THRESHOLD, assertEquals(OPENING_THRESHOLD, breaker.getClosingThreshold(), "Wrong closing threshold");
breaker.getClosingThreshold());
} }
/** /**
@ -87,8 +85,8 @@ public class EventCountCircuitBreakerTest {
public void testInitiallyClosed() { public void testInitiallyClosed() {
final EventCountCircuitBreaker breaker = new EventCountCircuitBreaker(OPENING_THRESHOLD, 1, final EventCountCircuitBreaker breaker = new EventCountCircuitBreaker(OPENING_THRESHOLD, 1,
TimeUnit.SECONDS); TimeUnit.SECONDS);
assertFalse("Open", breaker.isOpen()); assertFalse(breaker.isOpen(), "Open");
assertTrue("Not closed", breaker.isClosed()); assertTrue(breaker.isClosed(), "Not closed");
} }
/** /**
@ -100,7 +98,7 @@ public class EventCountCircuitBreakerTest {
TimeUnit.SECONDS); TimeUnit.SECONDS);
final long now = breaker.now(); final long now = breaker.now();
final long delta = Math.abs(System.nanoTime() - now); final long delta = Math.abs(System.nanoTime() - now);
assertTrue(String.format("Delta %d ns to current time too large", delta), delta < 100000); assertTrue(delta < 100000, String.format("Delta %d ns to current time too large", delta));
} }
/** /**
@ -113,10 +111,10 @@ public class EventCountCircuitBreakerTest {
final EventCountCircuitBreakerTestImpl breaker = new EventCountCircuitBreakerTestImpl(OPENING_THRESHOLD, 1, final EventCountCircuitBreakerTestImpl breaker = new EventCountCircuitBreakerTestImpl(OPENING_THRESHOLD, 1,
TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS); TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS);
for (int i = 0; i < OPENING_THRESHOLD - 1; i++) { for (int i = 0; i < OPENING_THRESHOLD - 1; i++) {
assertTrue("In open state", breaker.at(startTime).incrementAndCheckState()); assertTrue(breaker.at(startTime).incrementAndCheckState(), "In open state");
startTime++; startTime++;
} }
assertTrue("Not closed", breaker.isClosed()); assertTrue(breaker.isClosed(), "Not closed");
} }
/** /**
@ -130,10 +128,10 @@ public class EventCountCircuitBreakerTest {
final EventCountCircuitBreakerTestImpl breaker = new EventCountCircuitBreakerTestImpl(OPENING_THRESHOLD, 1, final EventCountCircuitBreakerTestImpl breaker = new EventCountCircuitBreakerTestImpl(OPENING_THRESHOLD, 1,
TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS); TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS);
for (int i = 0; i < 5 * OPENING_THRESHOLD; i++) { for (int i = 0; i < 5 * OPENING_THRESHOLD; i++) {
assertTrue("In open state", breaker.at(startTime).incrementAndCheckState()); assertTrue(breaker.at(startTime).incrementAndCheckState(), "In open state");
startTime += timeIncrement; startTime += timeIncrement;
} }
assertTrue("Not closed", breaker.isClosed()); assertTrue(breaker.isClosed(), "Not closed");
} }
/** /**
@ -150,8 +148,8 @@ public class EventCountCircuitBreakerTest {
open = !breaker.at(startTime).incrementAndCheckState(); open = !breaker.at(startTime).incrementAndCheckState();
startTime += timeIncrement; startTime += timeIncrement;
} }
assertTrue("Not open", open); assertTrue(open, "Not open");
assertFalse("Closed", breaker.isClosed()); assertFalse(breaker.isClosed(), "Closed");
} }
/** /**
@ -165,8 +163,8 @@ public class EventCountCircuitBreakerTest {
TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS); TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS);
long startTime = timeIncrement * (OPENING_THRESHOLD + 1); long startTime = timeIncrement * (OPENING_THRESHOLD + 1);
boolean open = !breaker.at(startTime).incrementAndCheckState(OPENING_THRESHOLD + 1); boolean open = !breaker.at(startTime).incrementAndCheckState(OPENING_THRESHOLD + 1);
assertTrue("Not open", open); assertTrue(open, "Not open");
assertFalse("Closed", breaker.isClosed()); assertFalse(breaker.isClosed(), "Closed");
} }
/** /**
@ -180,12 +178,11 @@ public class EventCountCircuitBreakerTest {
long startTime = 0; long startTime = 0;
breaker.open(); breaker.open();
for (int i = 0; i <= CLOSING_THRESHOLD; i++) { for (int i = 0; i <= CLOSING_THRESHOLD; i++) {
assertFalse("Not open", breaker.at(startTime).incrementAndCheckState()); assertFalse(breaker.at(startTime).incrementAndCheckState(), "Not open");
startTime += 1000; startTime += 1000;
} }
assertFalse("Closed in new interval", breaker.at(startTime + NANO_FACTOR) assertFalse(breaker.at(startTime + NANO_FACTOR).incrementAndCheckState(), "Closed in new interval");
.incrementAndCheckState()); assertTrue(breaker.isOpen(), "Not open at end");
assertTrue("Not open at end", breaker.isOpen());
} }
/** /**
@ -198,11 +195,10 @@ public class EventCountCircuitBreakerTest {
10, TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS); 10, TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS);
breaker.open(); breaker.open();
breaker.at(1000).incrementAndCheckState(); breaker.at(1000).incrementAndCheckState();
assertFalse("Already closed", breaker.at(2000).checkState()); assertFalse(breaker.at(2000).checkState(), "Already closed");
assertFalse("Closed at interval end", breaker.at(NANO_FACTOR).checkState()); assertFalse(breaker.at(NANO_FACTOR).checkState(), "Closed at interval end");
assertTrue("Not closed after interval end", breaker.at(NANO_FACTOR + 1) assertTrue(breaker.at(NANO_FACTOR + 1).checkState(), "Not closed after interval end");
.checkState()); assertTrue(breaker.isClosed(), "Not closed at end");
assertTrue("Not closed at end", breaker.isClosed());
} }
/** /**
@ -214,8 +210,8 @@ public class EventCountCircuitBreakerTest {
final EventCountCircuitBreakerTestImpl breaker = new EventCountCircuitBreakerTestImpl(OPENING_THRESHOLD, 2, final EventCountCircuitBreakerTestImpl breaker = new EventCountCircuitBreakerTestImpl(OPENING_THRESHOLD, 2,
TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS); TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS);
breaker.at(NANO_FACTOR - 1000).open(); breaker.at(NANO_FACTOR - 1000).open();
assertTrue("Not open", breaker.isOpen()); assertTrue(breaker.isOpen(), "Not open");
assertFalse("Already closed", breaker.at(NANO_FACTOR + 100).checkState()); assertFalse(breaker.at(NANO_FACTOR + 100).checkState(), "Already closed");
} }
/** /**
@ -230,11 +226,11 @@ public class EventCountCircuitBreakerTest {
for (int i = 0; i <= OPENING_THRESHOLD; i++) { for (int i = 0; i <= OPENING_THRESHOLD; i++) {
breaker.at(time++).incrementAndCheckState(); breaker.at(time++).incrementAndCheckState();
} }
assertTrue("Not open", breaker.isOpen()); assertTrue(breaker.isOpen(), "Not open");
time += NANO_FACTOR - 1000; time += NANO_FACTOR - 1000;
assertFalse("Already closed", breaker.at(time).incrementAndCheckState()); assertFalse(breaker.at(time).incrementAndCheckState(), "Already closed");
time += 1001; time += 1001;
assertTrue("Not closed in time interval", breaker.at(time).checkState()); assertTrue(breaker.at(time).checkState(), "Not closed in time interval");
} }
/** /**
@ -248,10 +244,10 @@ public class EventCountCircuitBreakerTest {
for (int i = 0; i <= OPENING_THRESHOLD; i++, time += 1000) { for (int i = 0; i <= OPENING_THRESHOLD; i++, time += 1000) {
breaker.at(time).incrementAndCheckState(); breaker.at(time).incrementAndCheckState();
} }
assertTrue("Not open", breaker.isOpen()); assertTrue(breaker.isOpen(), "Not open");
breaker.close(); breaker.close();
assertTrue("Not closed", breaker.isClosed()); assertTrue(breaker.isClosed(), "Not closed");
assertTrue("Open again", breaker.at(time + 1000).incrementAndCheckState()); assertTrue(breaker.at(time + 1000).incrementAndCheckState(), "Open again");
} }
/** /**
@ -396,11 +392,11 @@ public class EventCountCircuitBreakerTest {
@Override @Override
public void propertyChange(final PropertyChangeEvent evt) { public void propertyChange(final PropertyChangeEvent evt) {
assertEquals("Wrong event source", expectedSource, evt.getSource()); assertEquals(expectedSource, evt.getSource(), "Wrong event source");
assertEquals("Wrong property name", "open", evt.getPropertyName()); assertEquals("open", evt.getPropertyName(), "Wrong property name");
final Boolean newValue = (Boolean) evt.getNewValue(); final Boolean newValue = (Boolean) evt.getNewValue();
final Boolean oldValue = (Boolean) evt.getOldValue(); final Boolean oldValue = (Boolean) evt.getOldValue();
assertNotEquals("Old and new value are equal", newValue, oldValue); assertNotEquals(newValue, oldValue, "Old and new value are equal");
changedValues.add(newValue); changedValues.add(newValue);
} }

View File

@ -16,7 +16,7 @@
*/ */
package org.apache.commons.lang3.concurrent; package org.apache.commons.lang3.concurrent;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
/** /**
* Test class for {@code LazyInitializer}. * Test class for {@code LazyInitializer}.
@ -25,7 +25,7 @@ public class LazyInitializerTest extends AbstractConcurrentInitializerTest {
/** The initializer to be tested. */ /** The initializer to be tested. */
private LazyInitializerTestImpl initializer; private LazyInitializerTestImpl initializer;
@Before @BeforeEach
public void setUp() throws Exception { public void setUp() throws Exception {
initializer = new LazyInitializerTestImpl(); initializer = new LazyInitializerTestImpl();
} }

View File

@ -16,22 +16,25 @@
*/ */
package org.apache.commons.lang3.concurrent; package org.apache.commons.lang3.concurrent;
import org.easymock.EasyMockRunner; import org.easymock.EasyMock;
import org.easymock.Mock; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
import org.junit.runner.RunWith;
import static org.easymock.EasyMock.expect; import static org.easymock.EasyMock.expect;
import static org.easymock.EasyMock.replay; import static org.easymock.EasyMock.replay;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.fail;
@RunWith(EasyMockRunner.class)
public class MemoizerTest { public class MemoizerTest {
@Mock
private Computable<Integer, Integer> computable; private Computable<Integer, Integer> computable;
@BeforeEach
public void setUpComputableMock() {
computable = EasyMock.mock(Computable.class);
}
@Test @Test
public void testOnlyCallComputableOnceIfDoesNotThrowException() throws Exception { public void testOnlyCallComputableOnceIfDoesNotThrowException() throws Exception {
final Integer input = 1; final Integer input = 1;
@ -39,11 +42,11 @@ public class MemoizerTest {
expect(computable.compute(input)).andReturn(input); expect(computable.compute(input)).andReturn(input);
replay(computable); replay(computable);
assertEquals("Should call computable first time", input, memoizer.compute(input)); assertEquals(input, memoizer.compute(input), "Should call computable first time");
assertEquals("Should not call the computable the second time", input, memoizer.compute(input)); assertEquals(input, memoizer.compute(input), "Should not call the computable the second time");
} }
@Test(expected = IllegalStateException.class) @Test
public void testDefaultBehaviourNotToRecalculateExecutionExceptions() throws Exception { public void testDefaultBehaviourNotToRecalculateExecutionExceptions() throws Exception {
final Integer input = 1; final Integer input = 1;
final Memoizer<Integer, Integer> memoizer = new Memoizer<>(computable); final Memoizer<Integer, Integer> memoizer = new Memoizer<>(computable);
@ -58,10 +61,10 @@ public class MemoizerTest {
// Should always be thrown the first time // Should always be thrown the first time
} }
memoizer.compute(input); assertThrows(IllegalStateException.class, () -> memoizer.compute(input));
} }
@Test(expected = IllegalStateException.class) @Test
public void testDoesNotRecalculateWhenSetToFalse() throws Exception { public void testDoesNotRecalculateWhenSetToFalse() throws Exception {
final Integer input = 1; final Integer input = 1;
final Memoizer<Integer, Integer> memoizer = new Memoizer<>(computable, false); final Memoizer<Integer, Integer> memoizer = new Memoizer<>(computable, false);
@ -76,7 +79,7 @@ public class MemoizerTest {
// Should always be thrown the first time // Should always be thrown the first time
} }
memoizer.compute(input); assertThrows(IllegalStateException.class, () -> memoizer.compute(input));
} }
@Test @Test
@ -98,7 +101,7 @@ public class MemoizerTest {
assertEquals(answer, memoizer.compute(input)); assertEquals(answer, memoizer.compute(input));
} }
@Test(expected = RuntimeException.class) @Test
public void testWhenComputableThrowsRuntimeException() throws Exception { public void testWhenComputableThrowsRuntimeException() throws Exception {
final Integer input = 1; final Integer input = 1;
final Memoizer<Integer, Integer> memoizer = new Memoizer<>(computable); final Memoizer<Integer, Integer> memoizer = new Memoizer<>(computable);
@ -106,10 +109,10 @@ public class MemoizerTest {
expect(computable.compute(input)).andThrow(runtimeException); expect(computable.compute(input)).andThrow(runtimeException);
replay(computable); replay(computable);
memoizer.compute(input); assertThrows(RuntimeException.class, () -> memoizer.compute(input));
} }
@Test(expected = Error.class) @Test
public void testWhenComputableThrowsError() throws Exception { public void testWhenComputableThrowsError() throws Exception {
final Integer input = 1; final Integer input = 1;
final Memoizer<Integer, Integer> memoizer = new Memoizer<>(computable); final Memoizer<Integer, Integer> memoizer = new Memoizer<>(computable);
@ -117,6 +120,6 @@ public class MemoizerTest {
expect(computable.compute(input)).andThrow(error); expect(computable.compute(input)).andThrow(error);
replay(computable); replay(computable);
memoizer.compute(input); assertThrows(Error.class, () -> memoizer.compute(input));
} }
} }

View File

@ -16,11 +16,12 @@
*/ */
package org.apache.commons.lang3.concurrent; package org.apache.commons.lang3.concurrent;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.Assert.assertNull; import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.Iterator; import java.util.Iterator;
import java.util.NoSuchElementException; import java.util.NoSuchElementException;
@ -28,8 +29,8 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.junit.Before; import org.junit.jupiter.api.BeforeEach;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* Test class for {@link MultiBackgroundInitializer}. * Test class for {@link MultiBackgroundInitializer}.
@ -41,7 +42,7 @@ public class MultiBackgroundInitializerTest {
/** The initializer to be tested. */ /** The initializer to be tested. */
private MultiBackgroundInitializer initializer; private MultiBackgroundInitializer initializer;
@Before @BeforeEach
public void setUp() throws Exception { public void setUp() throws Exception {
initializer = new MultiBackgroundInitializer(); initializer = new MultiBackgroundInitializer();
} }
@ -59,11 +60,10 @@ public class MultiBackgroundInitializerTest {
final ExecutorService expExec) throws ConcurrentException { final ExecutorService expExec) throws ConcurrentException {
final ChildBackgroundInitializer cinit = (ChildBackgroundInitializer) child; final ChildBackgroundInitializer cinit = (ChildBackgroundInitializer) child;
final Integer result = cinit.get(); final Integer result = cinit.get();
assertEquals("Wrong result", 1, result.intValue()); assertEquals(1, result.intValue(), "Wrong result");
assertEquals("Wrong number of executions", 1, cinit.initializeCalls); assertEquals(1, cinit.initializeCalls, "Wrong number of executions");
if (expExec != null) { if (expExec != null) {
assertEquals("Wrong executor service", expExec, assertEquals(expExec, cinit.currentExecutor, "Wrong executor service");
cinit.currentExecutor);
} }
} }
@ -71,18 +71,18 @@ public class MultiBackgroundInitializerTest {
* Tests addInitializer() if a null name is passed in. This should cause an * Tests addInitializer() if a null name is passed in. This should cause an
* exception. * exception.
*/ */
@Test(expected = IllegalArgumentException.class) @Test
public void testAddInitializerNullName() { public void testAddInitializerNullName() {
initializer.addInitializer(null, new ChildBackgroundInitializer()); assertThrows(IllegalArgumentException.class, () -> initializer.addInitializer(null, new ChildBackgroundInitializer()));
} }
/** /**
* Tests addInitializer() if a null initializer is passed in. This should * Tests addInitializer() if a null initializer is passed in. This should
* cause an exception. * cause an exception.
*/ */
@Test(expected = IllegalArgumentException.class) @Test
public void testAddInitializerNullInit() { public void testAddInitializerNullInit() {
initializer.addInitializer(CHILD_INIT, null); assertThrows(IllegalArgumentException.class, () -> initializer.addInitializer(CHILD_INIT, null));
} }
/** /**
@ -92,12 +92,11 @@ public class MultiBackgroundInitializerTest {
*/ */
@Test @Test
public void testInitializeNoChildren() throws ConcurrentException { public void testInitializeNoChildren() throws ConcurrentException {
assertTrue("Wrong result of start()", initializer.start()); assertTrue(initializer.start(), "Wrong result of start()");
final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer
.get(); .get();
assertTrue("Got child initializers", res.initializerNames().isEmpty()); assertTrue(res.initializerNames().isEmpty(), "Got child initializers");
assertTrue("Executor not shutdown", initializer.getActiveExecutor() assertTrue(initializer.getActiveExecutor().isShutdown(), "Executor not shutdown");
.isShutdown());
} }
/** /**
@ -118,16 +117,13 @@ public class MultiBackgroundInitializerTest {
initializer.start(); initializer.start();
final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer
.get(); .get();
assertEquals("Wrong number of child initializers", count, res assertEquals(count, res.initializerNames().size(), "Wrong number of child initializers");
.initializerNames().size());
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
final String key = CHILD_INIT + i; final String key = CHILD_INIT + i;
assertTrue("Name not found: " + key, res.initializerNames() assertTrue(res.initializerNames().contains(key), "Name not found: " + key);
.contains(key)); assertEquals(Integer.valueOf(1), res.getResultObject(key), "Wrong result object");
assertEquals("Wrong result object", Integer.valueOf(1), res assertFalse(res.isException(key), "Exception flag");
.getResultObject(key)); assertNull(res.getException(key), "Got an exception");
assertFalse("Exception flag", res.isException(key));
assertNull("Got an exception", res.getException(key));
checkChild(res.getInitializer(key), initializer.getActiveExecutor()); checkChild(res.getInitializer(key), initializer.getActiveExecutor());
} }
return res; return res;
@ -141,8 +137,7 @@ public class MultiBackgroundInitializerTest {
@Test @Test
public void testInitializeTempExec() throws ConcurrentException { public void testInitializeTempExec() throws ConcurrentException {
checkInitialize(); checkInitialize();
assertTrue("Executor not shutdown", initializer.getActiveExecutor() assertTrue(initializer.getActiveExecutor().isShutdown(), "Executor not shutdown");
.isShutdown());
} }
/** /**
@ -156,9 +151,8 @@ public class MultiBackgroundInitializerTest {
try { try {
initializer = new MultiBackgroundInitializer(exec); initializer = new MultiBackgroundInitializer(exec);
checkInitialize(); checkInitialize();
assertEquals("Wrong executor", exec, initializer assertEquals(exec, initializer.getActiveExecutor(), "Wrong executor");
.getActiveExecutor()); assertFalse(exec.isShutdown(), "Executor was shutdown");
assertFalse("Executor was shutdown", exec.isShutdown());
} finally { } finally {
exec.shutdown(); exec.shutdown();
exec.awaitTermination(1, TimeUnit.SECONDS); exec.awaitTermination(1, TimeUnit.SECONDS);
@ -215,10 +209,10 @@ public class MultiBackgroundInitializerTest {
* *
* @throws org.apache.commons.lang3.concurrent.ConcurrentException so we don't have to catch it * @throws org.apache.commons.lang3.concurrent.ConcurrentException so we don't have to catch it
*/ */
@Test(expected = NoSuchElementException.class) @Test
public void testResultGetInitializerUnknown() throws ConcurrentException { public void testResultGetInitializerUnknown() throws ConcurrentException {
final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = checkInitialize(); final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = checkInitialize();
res.getInitializer("unknown"); assertThrows(NoSuchElementException.class, () -> res.getInitializer("unknown"));
} }
/** /**
@ -227,10 +221,10 @@ public class MultiBackgroundInitializerTest {
* *
* @throws org.apache.commons.lang3.concurrent.ConcurrentException so we don't have to catch it * @throws org.apache.commons.lang3.concurrent.ConcurrentException so we don't have to catch it
*/ */
@Test(expected = NoSuchElementException.class) @Test
public void testResultGetResultObjectUnknown() throws ConcurrentException { public void testResultGetResultObjectUnknown() throws ConcurrentException {
final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = checkInitialize(); final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = checkInitialize();
res.getResultObject("unknown"); assertThrows(NoSuchElementException.class, () -> res.getResultObject("unknown"));
} }
/** /**
@ -239,10 +233,10 @@ public class MultiBackgroundInitializerTest {
* *
* @throws org.apache.commons.lang3.concurrent.ConcurrentException so we don't have to catch it * @throws org.apache.commons.lang3.concurrent.ConcurrentException so we don't have to catch it
*/ */
@Test(expected = NoSuchElementException.class) @Test
public void testResultGetExceptionUnknown() throws ConcurrentException { public void testResultGetExceptionUnknown() throws ConcurrentException {
final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = checkInitialize(); final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = checkInitialize();
res.getException("unknown"); assertThrows(NoSuchElementException.class, () -> res.getException("unknown"));
} }
/** /**
@ -251,10 +245,10 @@ public class MultiBackgroundInitializerTest {
* *
* @throws org.apache.commons.lang3.concurrent.ConcurrentException so we don't have to catch it * @throws org.apache.commons.lang3.concurrent.ConcurrentException so we don't have to catch it
*/ */
@Test(expected = NoSuchElementException.class) @Test
public void testResultIsExceptionUnknown() throws ConcurrentException { public void testResultIsExceptionUnknown() throws ConcurrentException {
final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = checkInitialize(); final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = checkInitialize();
res.isException("unknown"); assertThrows(NoSuchElementException.class, () -> res.isException("unknown"));
} }
/** /**
@ -262,14 +256,14 @@ public class MultiBackgroundInitializerTest {
* *
* @throws org.apache.commons.lang3.concurrent.ConcurrentException so we don't have to catch it * @throws org.apache.commons.lang3.concurrent.ConcurrentException so we don't have to catch it
*/ */
@Test(expected = UnsupportedOperationException.class) @Test
public void testResultInitializerNamesModify() throws ConcurrentException { public void testResultInitializerNamesModify() throws ConcurrentException {
checkInitialize(); checkInitialize();
final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer
.get(); .get();
final Iterator<String> it = res.initializerNames().iterator(); final Iterator<String> it = res.initializerNames().iterator();
it.next(); it.next();
it.remove(); assertThrows(UnsupportedOperationException.class, it::remove);
} }
/** /**
@ -286,7 +280,7 @@ public class MultiBackgroundInitializerTest {
initializer.get(); initializer.get();
fail("Runtime exception not thrown!"); fail("Runtime exception not thrown!");
} catch (final Exception ex) { } catch (final Exception ex) {
assertEquals("Wrong exception", child.ex, ex); assertEquals(child.ex, ex, "Wrong exception");
} }
} }
@ -304,10 +298,10 @@ public class MultiBackgroundInitializerTest {
initializer.start(); initializer.start();
final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer
.get(); .get();
assertTrue("No exception flag", res.isException(CHILD_INIT)); assertTrue(res.isException(CHILD_INIT), "No exception flag");
assertNull("Got a results object", res.getResultObject(CHILD_INIT)); assertNull(res.getResultObject(CHILD_INIT), "Got a results object");
final ConcurrentException cex = res.getException(CHILD_INIT); final ConcurrentException cex = res.getException(CHILD_INIT);
assertEquals("Wrong cause", child.ex, cex.getCause()); assertEquals(child.ex, cex.getCause(), "Wrong cause");
} }
/** /**
@ -324,7 +318,7 @@ public class MultiBackgroundInitializerTest {
initializer.start(); initializer.start();
final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer
.get(); .get();
assertTrue("Wrong success flag", res.isSuccessful()); assertTrue(res.isSuccessful(), "Wrong success flag");
} }
/** /**
@ -342,7 +336,7 @@ public class MultiBackgroundInitializerTest {
initializer.start(); initializer.start();
final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer
.get(); .get();
assertFalse("Wrong success flag", res.isSuccessful()); assertFalse(res.isSuccessful(), "Wrong success flag");
} }
/** /**
@ -371,12 +365,11 @@ public class MultiBackgroundInitializerTest {
checkChild(res.getInitializer(CHILD_INIT), exec); checkChild(res.getInitializer(CHILD_INIT), exec);
final MultiBackgroundInitializer.MultiBackgroundInitializerResults res2 = (MultiBackgroundInitializer.MultiBackgroundInitializerResults) res final MultiBackgroundInitializer.MultiBackgroundInitializerResults res2 = (MultiBackgroundInitializer.MultiBackgroundInitializerResults) res
.getResultObject(nameMulti); .getResultObject(nameMulti);
assertEquals("Wrong number of initializers", count, res2 assertEquals(count, res2.initializerNames().size(), "Wrong number of initializers");
.initializerNames().size());
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
checkChild(res2.getInitializer(CHILD_INIT + i), exec); checkChild(res2.getInitializer(CHILD_INIT + i), exec);
} }
assertTrue("Executor not shutdown", exec.isShutdown()); assertTrue(exec.isShutdown(), "Executor not shutdown");
} }
/** /**

View File

@ -16,11 +16,11 @@
*/ */
package org.apache.commons.lang3.concurrent; package org.apache.commons.lang3.concurrent;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* Test class for {@code ThresholdCircuitBreaker}. * Test class for {@code ThresholdCircuitBreaker}.
@ -41,7 +41,7 @@ public class ThresholdCircuitBreakerTest {
public void testThreshold() { public void testThreshold() {
final ThresholdCircuitBreaker circuit = new ThresholdCircuitBreaker(threshold); final ThresholdCircuitBreaker circuit = new ThresholdCircuitBreaker(threshold);
circuit.incrementAndCheckState(9L); circuit.incrementAndCheckState(9L);
assertFalse("Circuit opened before reaching the threshold", circuit.incrementAndCheckState(1L)); assertFalse(circuit.incrementAndCheckState(1L), "Circuit opened before reaching the threshold");
} }
/** /**
@ -51,7 +51,7 @@ public class ThresholdCircuitBreakerTest {
public void testThresholdCircuitBreakingException() { public void testThresholdCircuitBreakingException() {
final ThresholdCircuitBreaker circuit = new ThresholdCircuitBreaker(threshold); final ThresholdCircuitBreaker circuit = new ThresholdCircuitBreaker(threshold);
circuit.incrementAndCheckState(9L); circuit.incrementAndCheckState(9L);
assertTrue("The circuit was supposed to be open after increment above the threshold", circuit.incrementAndCheckState(2L)); assertTrue(circuit.incrementAndCheckState(2L), "The circuit was supposed to be open after increment above the threshold");
} }
/** /**
@ -60,7 +60,7 @@ public class ThresholdCircuitBreakerTest {
@Test @Test
public void testThresholdEqualsZero() { public void testThresholdEqualsZero() {
final ThresholdCircuitBreaker circuit = new ThresholdCircuitBreaker(zeroThreshold); final ThresholdCircuitBreaker circuit = new ThresholdCircuitBreaker(zeroThreshold);
assertTrue("When the threshold is zero, the circuit is supposed to be always open", circuit.incrementAndCheckState(0L)); assertTrue(circuit.incrementAndCheckState(0L), "When the threshold is zero, the circuit is supposed to be always open");
} }
/** /**
@ -72,7 +72,7 @@ public class ThresholdCircuitBreakerTest {
circuit.incrementAndCheckState(9L); circuit.incrementAndCheckState(9L);
circuit.close(); circuit.close();
// now the internal counter is back at zero, not 9 anymore. So it is safe to increment 9 again // now the internal counter is back at zero, not 9 anymore. So it is safe to increment 9 again
assertFalse("Internal counter was not reset back to zero", circuit.incrementAndCheckState(9L)); assertFalse(circuit.incrementAndCheckState(9L), "Internal counter was not reset back to zero");
} }
/** /**
@ -81,7 +81,7 @@ public class ThresholdCircuitBreakerTest {
@Test @Test
public void testGettingThreshold() { public void testGettingThreshold() {
final ThresholdCircuitBreaker circuit = new ThresholdCircuitBreaker(threshold); final ThresholdCircuitBreaker circuit = new ThresholdCircuitBreaker(threshold);
assertEquals("Wrong value of threshold", Long.valueOf(threshold), Long.valueOf(circuit.getThreshold())); assertEquals(Long.valueOf(threshold), Long.valueOf(circuit.getThreshold()), "Wrong value of threshold");
} }
} }

View File

@ -16,11 +16,12 @@
*/ */
package org.apache.commons.lang3.concurrent; package org.apache.commons.lang3.concurrent;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.Assert.assertFalse; import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.Assert.assertTrue; import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.Assert.fail; import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledExecutorService;
@ -29,7 +30,7 @@ import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import org.easymock.EasyMock; import org.easymock.EasyMock;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* Test class for TimedSemaphore. * Test class for TimedSemaphore.
@ -55,24 +56,22 @@ public class TimedSemaphoreTest {
final TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD, UNIT, final TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD, UNIT,
LIMIT); LIMIT);
EasyMock.verify(service); EasyMock.verify(service);
assertEquals("Wrong service", service, semaphore.getExecutorService()); assertEquals(service, semaphore.getExecutorService(), "Wrong service");
assertEquals("Wrong period", PERIOD, semaphore.getPeriod()); assertEquals(PERIOD, semaphore.getPeriod(), "Wrong period");
assertEquals("Wrong unit", UNIT, semaphore.getUnit()); assertEquals(UNIT, semaphore.getUnit(), "Wrong unit");
assertEquals("Statistic available", 0, semaphore assertEquals(0, semaphore.getLastAcquiresPerPeriod(), "Statistic available");
.getLastAcquiresPerPeriod()); assertEquals(0.0, semaphore.getAverageCallsPerPeriod(), .05, "Average available");
assertEquals("Average available", 0.0, semaphore assertFalse(semaphore.isShutdown(), "Already shutdown");
.getAverageCallsPerPeriod(), .05); assertEquals(LIMIT, semaphore.getLimit(), "Wrong limit");
assertFalse("Already shutdown", semaphore.isShutdown());
assertEquals("Wrong limit", LIMIT, semaphore.getLimit());
} }
/** /**
* Tries to create an instance with a negative period. This should cause an * Tries to create an instance with a negative period. This should cause an
* exception. * exception.
*/ */
@Test(expected = IllegalArgumentException.class) @Test
public void testInitInvalidPeriod() { public void testInitInvalidPeriod() {
new TimedSemaphore(0L, UNIT, LIMIT); assertThrows(IllegalArgumentException.class, () -> new TimedSemaphore(0L, UNIT, LIMIT));
} }
/** /**
@ -84,11 +83,9 @@ public class TimedSemaphoreTest {
final TimedSemaphore semaphore = new TimedSemaphore(PERIOD, UNIT, LIMIT); final TimedSemaphore semaphore = new TimedSemaphore(PERIOD, UNIT, LIMIT);
final ScheduledThreadPoolExecutor exec = (ScheduledThreadPoolExecutor) semaphore final ScheduledThreadPoolExecutor exec = (ScheduledThreadPoolExecutor) semaphore
.getExecutorService(); .getExecutorService();
assertFalse("Wrong periodic task policy", exec assertFalse(exec.getContinueExistingPeriodicTasksAfterShutdownPolicy(), "Wrong periodic task policy");
.getContinueExistingPeriodicTasksAfterShutdownPolicy()); assertFalse(exec.getExecuteExistingDelayedTasksAfterShutdownPolicy(), "Wrong delayed task policy");
assertFalse("Wrong delayed task policy", exec assertFalse(exec.isShutdown(), "Already shutdown");
.getExecuteExistingDelayedTasksAfterShutdownPolicy());
assertFalse("Already shutdown", exec.isShutdown());
semaphore.shutdown(); semaphore.shutdown();
} }
@ -102,7 +99,7 @@ public class TimedSemaphoreTest {
final TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(PERIOD, final TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(PERIOD,
UNIT, LIMIT); UNIT, LIMIT);
final ScheduledFuture<?> future = semaphore.startTimer(); final ScheduledFuture<?> future = semaphore.startTimer();
assertNotNull("No future returned", future); assertNotNull(future, "No future returned");
Thread.sleep(PERIOD); Thread.sleep(PERIOD);
final int trials = 10; final int trials = 10;
int count = 0; int count = 0;
@ -123,9 +120,8 @@ public class TimedSemaphoreTest {
public void testShutdownOwnExecutor() { public void testShutdownOwnExecutor() {
final TimedSemaphore semaphore = new TimedSemaphore(PERIOD, UNIT, LIMIT); final TimedSemaphore semaphore = new TimedSemaphore(PERIOD, UNIT, LIMIT);
semaphore.shutdown(); semaphore.shutdown();
assertTrue("Not shutdown", semaphore.isShutdown()); assertTrue(semaphore.isShutdown(), "Not shutdown");
assertTrue("Executor not shutdown", semaphore.getExecutorService() assertTrue(semaphore.getExecutorService().isShutdown(), "Executor not shutdown");
.isShutdown());
} }
/** /**
@ -140,7 +136,7 @@ public class TimedSemaphoreTest {
final TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD, UNIT, final TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD, UNIT,
LIMIT); LIMIT);
semaphore.shutdown(); semaphore.shutdown();
assertTrue("Not shutdown", semaphore.isShutdown()); assertTrue(semaphore.isShutdown(), "Not shutdown");
EasyMock.verify(service); EasyMock.verify(service);
} }
@ -175,7 +171,7 @@ public class TimedSemaphoreTest {
PERIOD, UNIT, LIMIT); PERIOD, UNIT, LIMIT);
semaphore.acquire(); semaphore.acquire();
semaphore.shutdown(); semaphore.shutdown();
assertTrue("Not shutdown", semaphore.isShutdown()); assertTrue(semaphore.isShutdown(), "Not shutdown");
EasyMock.verify(service, future); EasyMock.verify(service, future);
} }
@ -224,16 +220,13 @@ public class TimedSemaphoreTest {
t.start(); t.start();
latch.await(); latch.await();
// now the semaphore's limit should be reached and the thread blocked // now the semaphore's limit should be reached and the thread blocked
assertEquals("Wrong semaphore count", count - 1, semaphore assertEquals(count - 1, semaphore.getAcquireCount(), "Wrong semaphore count");
.getAcquireCount());
// this wakes up the thread, it should call the semaphore once more // this wakes up the thread, it should call the semaphore once more
semaphore.endOfPeriod(); semaphore.endOfPeriod();
t.join(); t.join();
assertEquals("Wrong semaphore count (2)", 1, semaphore assertEquals(1, semaphore.getAcquireCount(), "Wrong semaphore count (2)");
.getAcquireCount()); assertEquals(count - 1, semaphore.getLastAcquiresPerPeriod(), "Wrong acquire() count");
assertEquals("Wrong acquire() count", count - 1, semaphore
.getLastAcquiresPerPeriod());
EasyMock.verify(service, future); EasyMock.verify(service, future);
} }
@ -263,11 +256,10 @@ public class TimedSemaphoreTest {
} }
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
semaphore.latch.await(); semaphore.latch.await();
assertEquals("Wrong count", 1, semaphore.getAcquireCount()); assertEquals(1, semaphore.getAcquireCount(), "Wrong count");
semaphore.latch = new CountDownLatch(1); semaphore.latch = new CountDownLatch(1);
semaphore.endOfPeriod(); semaphore.endOfPeriod();
assertEquals("Wrong acquire count", 1, semaphore assertEquals(1, semaphore.getLastAcquiresPerPeriod(), "Wrong acquire count");
.getLastAcquiresPerPeriod());
} }
for (int i = 0; i < count; i++) { for (int i = 0; i < count; i++) {
threads[i].join(); threads[i].join();
@ -304,11 +296,11 @@ public class TimedSemaphoreTest {
* *
* @throws java.lang.InterruptedException so we don't have to catch it * @throws java.lang.InterruptedException so we don't have to catch it
*/ */
@Test(expected = IllegalStateException.class) @Test
public void testPassAfterShutdown() throws InterruptedException { public void testPassAfterShutdown() throws InterruptedException {
final TimedSemaphore semaphore = new TimedSemaphore(PERIOD, UNIT, LIMIT); final TimedSemaphore semaphore = new TimedSemaphore(PERIOD, UNIT, LIMIT);
semaphore.shutdown(); semaphore.shutdown();
semaphore.acquire(); assertThrows(IllegalStateException.class, semaphore::acquire);
} }
/** /**
@ -330,7 +322,7 @@ public class TimedSemaphoreTest {
t.start(); t.start();
latch.await(); latch.await();
semaphore.shutdown(); semaphore.shutdown();
assertTrue("End of period not reached", semaphore.getPeriodEnds() > 0); assertTrue(semaphore.getPeriodEnds() > 0, "End of period not reached");
} }
/** /**
@ -349,13 +341,11 @@ public class TimedSemaphoreTest {
LIMIT); LIMIT);
semaphore.acquire(); semaphore.acquire();
semaphore.endOfPeriod(); semaphore.endOfPeriod();
assertEquals("Wrong average (1)", 1.0, semaphore assertEquals(1.0, semaphore.getAverageCallsPerPeriod(), .005, "Wrong average (1)");
.getAverageCallsPerPeriod(), .005);
semaphore.acquire(); semaphore.acquire();
semaphore.acquire(); semaphore.acquire();
semaphore.endOfPeriod(); semaphore.endOfPeriod();
assertEquals("Wrong average (2)", 1.5, semaphore assertEquals(1.5, semaphore.getAverageCallsPerPeriod(), .005, "Wrong average (2)");
.getAverageCallsPerPeriod(), .005);
EasyMock.verify(service, future); EasyMock.verify(service, future);
} }
@ -374,13 +364,11 @@ public class TimedSemaphoreTest {
final TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD, UNIT, final TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD, UNIT,
LIMIT); LIMIT);
for (int i = 0; i < LIMIT; i++) { for (int i = 0; i < LIMIT; i++) {
assertEquals("Wrong available count at " + i, LIMIT - i, semaphore assertEquals(LIMIT - i, semaphore.getAvailablePermits(), "Wrong available count at " + i);
.getAvailablePermits());
semaphore.acquire(); semaphore.acquire();
} }
semaphore.endOfPeriod(); semaphore.endOfPeriod();
assertEquals("Wrong available count in new period", LIMIT, semaphore assertEquals(LIMIT, semaphore.getAvailablePermits(), "Wrong available count in new period");
.getAvailablePermits());
EasyMock.verify(service, future); EasyMock.verify(service, future);
} }
@ -407,17 +395,17 @@ public class TimedSemaphoreTest {
permits++; permits++;
} }
} }
assertEquals("Wrong number of permits granted", LIMIT, permits); assertEquals(LIMIT, permits, "Wrong number of permits granted");
} }
/** /**
* Tries to call tryAcquire() after shutdown(). This should cause an exception. * Tries to call tryAcquire() after shutdown(). This should cause an exception.
*/ */
@Test(expected = IllegalStateException.class) @Test
public void testTryAcquireAfterShutdown() { public void testTryAcquireAfterShutdown() {
final TimedSemaphore semaphore = new TimedSemaphore(PERIOD, UNIT, LIMIT); final TimedSemaphore semaphore = new TimedSemaphore(PERIOD, UNIT, LIMIT);
semaphore.shutdown(); semaphore.shutdown();
semaphore.tryAcquire(); assertThrows(IllegalStateException.class, semaphore::tryAcquire);
} }
/** /**