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;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.util.concurrent.CountDownLatch;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* <p>
@ -42,7 +42,7 @@ public abstract class AbstractConcurrentInitializerTest {
*/
@Test
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 Object obj = initializer.get();
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
final Object managedObject = initializer.get();
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;
import static org.junit.Assert.assertEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Test class for {@code AtomicSafeInitializer}.
@ -31,7 +31,7 @@ public class AtomicSafeInitializerTest extends
/** The instance to be tested. */
private AtomicSafeInitializerTestImpl initializer;
@Before
@BeforeEach
public void setUp() throws Exception {
initializer = new AtomicSafeInitializerTestImpl();
}
@ -56,8 +56,7 @@ public class AtomicSafeInitializerTest extends
public void testNumberOfInitializeInvocations() throws ConcurrentException,
InterruptedException {
testGetConcurrent();
assertEquals("Wrong number of invocations", 1,
initializer.initCounter.get());
assertEquals(1, initializer.initCounter.get(), "Wrong number of invocations");
}
/**

View File

@ -16,15 +16,16 @@
*/
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.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
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.ExecutorService;
@ -42,9 +43,9 @@ public class BackgroundInitializerTest {
private void checkInitialize(final BackgroundInitializerTestImpl init) {
try {
final Integer result = init.get();
assertEquals("Wrong result", 1, result.intValue());
assertEquals("Wrong number of invocations", 1, init.initializeCalls);
assertNotNull("No future", init.getFuture());
assertEquals(1, result.intValue(), "Wrong result");
assertEquals(1, init.initializeCalls, "Wrong number of invocations");
assertNotNull(init.getFuture(), "No future");
} catch (final ConcurrentException cex) {
fail("Unexpected exception: " + cex);
}
@ -67,7 +68,7 @@ public class BackgroundInitializerTest {
@Test
public void testGetActiveExecutorBeforeStart() {
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(
exec);
init.start();
assertSame("Wrong executor", exec, init.getActiveExecutor());
assertSame(exec, init.getActiveExecutor(), "Wrong executor");
checkInitialize(init);
} finally {
exec.shutdown();
@ -95,7 +96,7 @@ public class BackgroundInitializerTest {
public void testGetActiveExecutorTemp() {
final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
init.start();
assertNotNull("No active executor", init.getActiveExecutor());
assertNotNull(init.getActiveExecutor(), "No active executor");
checkInitialize(init);
}
@ -106,10 +107,9 @@ public class BackgroundInitializerTest {
@Test
public void testInitializeTempExecutor() {
final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
assertTrue("Wrong result of start()", init.start());
assertTrue(init.start(), "Wrong result of start()");
checkInitialize(init);
assertTrue("Executor not shutdown", init.getActiveExecutor()
.isShutdown());
assertTrue(init.getActiveExecutor().isShutdown(), "Executor not shutdown");
}
/**
@ -122,12 +122,11 @@ public class BackgroundInitializerTest {
try {
final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
init.setExternalExecutor(exec);
assertEquals("Wrong executor service", exec, init
.getExternalExecutor());
assertTrue("Wrong result of start()", init.start());
assertSame("Wrong active executor", exec, init.getActiveExecutor());
assertEquals(exec, init.getExternalExecutor(), "Wrong executor service");
assertTrue(init.start(), "Wrong result of start()");
assertSame(exec, init.getActiveExecutor(), "Wrong active executor");
checkInitialize(init);
assertFalse("Executor was shutdown", exec.isShutdown());
assertFalse(exec.isShutdown(), "Executor was shutdown");
} finally {
exec.shutdown();
}
@ -161,9 +160,9 @@ public class BackgroundInitializerTest {
@Test
public void testStartMultipleTimes() {
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++) {
assertFalse("Could start again", init.start());
assertFalse(init.start(), "Could start again");
}
checkInitialize(init);
}
@ -173,10 +172,10 @@ public class BackgroundInitializerTest {
*
* @throws org.apache.commons.lang3.concurrent.ConcurrentException because the test implementation may throw it
*/
@Test(expected=IllegalStateException.class)
@Test
public void testGetBeforeStart() throws ConcurrentException {
final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
init.get();
assertThrows(IllegalStateException.class, init::get);
}
/**
@ -193,7 +192,7 @@ public class BackgroundInitializerTest {
init.get();
fail("Exception not thrown!");
} 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();
fail("Exception not thrown!");
} 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());
}
} finally {
assertTrue("Thread not interrupted", isInterrupted());
assertTrue(isInterrupted(), "Thread not interrupted");
latch1.countDown();
}
}
@ -249,7 +248,7 @@ public class BackgroundInitializerTest {
latch1.await();
exec.shutdownNow();
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
public void testIsStartedFalse() {
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() {
final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
init.start();
assertTrue("Not started", init.isStarted());
assertTrue(init.isStarted(), "Not started");
}
/**
@ -279,7 +278,7 @@ public class BackgroundInitializerTest {
final BackgroundInitializerTestImpl init = new BackgroundInitializerTestImpl();
init.start();
checkInitialize(init);
assertTrue("Not started", init.isStarted());
assertTrue(init.isStarted(), "Not started");
}
/**

View File

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

View File

@ -16,14 +16,15 @@
*/
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.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* Test class for {@code CallableBackgroundInitializer}
@ -36,9 +37,9 @@ public class CallableBackgroundInitializerTest {
* Tries to create an instance without a Callable. This should cause an
* exception.
*/
@Test(expected=IllegalArgumentException.class)
@Test()
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 CallableBackgroundInitializer<Integer> init = new CallableBackgroundInitializer<>(
new TestCallable(), exec);
assertEquals("Executor not set", exec, init.getExternalExecutor());
assertEquals(exec, init.getExternalExecutor(), "Executor not set");
exec.shutdown();
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.
* This should cause an exception.
*/
@Test(expected=IllegalArgumentException.class)
@Test
public void testInitExecutorNullCallable() throws InterruptedException {
final ExecutorService exec = Executors.newSingleThreadExecutor();
try {
new CallableBackgroundInitializer<Integer>(null, exec);
assertThrows(IllegalArgumentException.class, () -> new CallableBackgroundInitializer<Integer>(null, exec));
} finally {
exec.shutdown();
exec.awaitTermination(1, TimeUnit.SECONDS);
@ -81,8 +82,8 @@ public class CallableBackgroundInitializerTest {
final TestCallable call = new TestCallable();
final CallableBackgroundInitializer<Integer> init = new CallableBackgroundInitializer<>(
call);
assertEquals("Wrong result", RESULT, init.initialize());
assertEquals("Wrong number of invocations", 1, call.callCount);
assertEquals(RESULT, init.initialize(), "Wrong result");
assertEquals(1, call.callCount, "Wrong number of invocations");
}
/**

View File

@ -17,11 +17,12 @@
package org.apache.commons.lang3.concurrent;
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.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
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 {
@Test(expected = CircuitBreakingException.class)
public void testThrowingInformativeException() throws Exception {
throw new CircuitBreakingException(EXCEPTION_MESSAGE, generateCause());
@Test
public void testThrowingInformativeException() {
assertThrows(CircuitBreakingException.class, () -> {
throw new CircuitBreakingException(EXCEPTION_MESSAGE, generateCause());
});
}
@Test(expected = CircuitBreakingException.class)
public void testThrowingExceptionWithMessage() throws Exception {
throw new CircuitBreakingException(EXCEPTION_MESSAGE);
@Test
public void testThrowingExceptionWithMessage() {
assertThrows(CircuitBreakingException.class, () -> {
throw new CircuitBreakingException(EXCEPTION_MESSAGE);
});
}
@Test(expected = CircuitBreakingException.class)
public void testThrowingExceptionWithCause() throws Exception {
throw new CircuitBreakingException(generateCause());
@Test
public void testThrowingExceptionWithCause() {
assertThrows(CircuitBreakingException.class, () -> {
throw new CircuitBreakingException(generateCause());
});
}
@Test(expected = CircuitBreakingException.class)
public void testThrowingEmptyException() throws Exception {
throw new CircuitBreakingException();
@Test
public void testThrowingEmptyException() {
assertThrows(CircuitBreakingException.class, () -> {
throw new CircuitBreakingException();
});
}
@Test
public void testWithCauseAndMessage() throws Exception {
final Exception exception = new CircuitBreakingException(EXCEPTION_MESSAGE, generateCause());
assertNotNull(exception);
assertEquals(WRONG_EXCEPTION_MESSAGE, EXCEPTION_MESSAGE, exception.getMessage());
assertEquals(EXCEPTION_MESSAGE, exception.getMessage(), WRONG_EXCEPTION_MESSAGE);
final Throwable cause = exception.getCause();
assertNotNull(cause);
assertEquals(WRONG_CAUSE_MESSAGE, CAUSE_MESSAGE, cause.getMessage());
assertEquals(CAUSE_MESSAGE, cause.getMessage(), WRONG_CAUSE_MESSAGE);
}
@Test
public void testWithoutCause() throws Exception {
final Exception exception = new CircuitBreakingException(EXCEPTION_MESSAGE);
assertNotNull(exception);
assertEquals(WRONG_EXCEPTION_MESSAGE, EXCEPTION_MESSAGE, exception.getMessage());
assertEquals(EXCEPTION_MESSAGE, exception.getMessage(), WRONG_EXCEPTION_MESSAGE);
final Throwable cause = exception.getCause();
assertNull(cause);
@ -78,6 +87,6 @@ public class CircuitBreakingExceptionTest extends AbstractExceptionTest {
final Throwable cause = exception.getCause();
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;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertThrows;
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.ConcurrentMap;
@ -31,7 +32,7 @@ import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import org.easymock.EasyMock;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* Test class for {@link ConcurrentUtils}.
@ -40,49 +41,49 @@ public class ConcurrentUtilsTest {
/**
* Tests creating a ConcurrentException with a runtime exception as cause.
*/
@Test(expected = IllegalArgumentException.class)
@Test
public void testConcurrentExceptionCauseUnchecked() {
new ConcurrentException(new RuntimeException());
assertThrows(IllegalArgumentException.class, () -> new ConcurrentException(new RuntimeException()));
}
/**
* Tests creating a ConcurrentException with an error as cause.
*/
@Test(expected = IllegalArgumentException.class)
@Test
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.
*/
@Test(expected = IllegalArgumentException.class)
@Test
public void testConcurrentExceptionCauseNull() {
new ConcurrentException(null);
assertThrows(IllegalArgumentException.class, () -> new ConcurrentException(null));
}
/**
* Tries to create a ConcurrentRuntimeException with a runtime as cause.
*/
@Test(expected = IllegalArgumentException.class)
@Test
public void testConcurrentRuntimeExceptionCauseUnchecked() {
new ConcurrentRuntimeException(new RuntimeException());
assertThrows(IllegalArgumentException.class, () -> new ConcurrentRuntimeException(new RuntimeException()));
}
/**
* Tries to create a ConcurrentRuntimeException with an error as cause.
*/
@Test(expected = IllegalArgumentException.class)
@Test
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.
*/
@Test(expected = IllegalArgumentException.class)
@Test
public void testConcurrentRuntimeExceptionCauseNull() {
new ConcurrentRuntimeException(null);
assertThrows(IllegalArgumentException.class, () -> new ConcurrentRuntimeException(null));
}
/**
@ -90,7 +91,7 @@ public class ConcurrentUtilsTest {
*/
@Test
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
public void testExtractCauseNullCause() {
assertNull("Non null result", ConcurrentUtils
.extractCause(new ExecutionException("Test", null)));
assertNull(ConcurrentUtils.extractCause(new ExecutionException("Test", null)), "Non null result");
}
/**
@ -112,7 +112,7 @@ public class ConcurrentUtilsTest {
ConcurrentUtils.extractCause(new ExecutionException(err));
fail("Error not thrown!");
} 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));
fail("Runtime exception not thrown!");
} 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 ConcurrentException cex = ConcurrentUtils
.extractCause(new ExecutionException(ex));
assertSame("Wrong cause", ex, cex.getCause());
assertSame(ex, cex.getCause(), "Wrong cause");
}
/**
@ -146,7 +146,7 @@ public class ConcurrentUtilsTest {
*/
@Test
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
public void testExtractCauseUncheckedNullCause() {
assertNull("Non null result", ConcurrentUtils
.extractCauseUnchecked(new ExecutionException("Test", null)));
assertNull(ConcurrentUtils.extractCauseUnchecked(new ExecutionException("Test", null)), "Non null result");
}
/**
@ -168,7 +167,7 @@ public class ConcurrentUtilsTest {
ConcurrentUtils.extractCauseUnchecked(new ExecutionException(err));
fail("Error not thrown!");
} 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));
fail("Runtime exception not thrown!");
} 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 ConcurrentRuntimeException cex = ConcurrentUtils
.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));
fail("Error not thrown!");
} 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));
fail("Runtime exception not thrown!");
} 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));
fail("ConcurrentException not thrown!");
} 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));
fail("Error not thrown!");
} 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));
fail("Runtime exception not thrown!");
} 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));
fail("ConcurrentRuntimeException not thrown!");
} catch (final ConcurrentRuntimeException crex) {
assertEquals("Wrong cause", ex, crex.getCause());
assertEquals(ex, crex.getCause(), "Wrong cause");
}
}
@ -318,7 +317,7 @@ public class ConcurrentUtilsTest {
*/
@Test
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();
EasyMock.expect(init.get()).andReturn(result);
EasyMock.replay(init);
assertSame("Wrong result object", result, ConcurrentUtils
.initialize(init));
assertSame(result, ConcurrentUtils.initialize(init), "Wrong result object");
EasyMock.verify(init);
}
@ -345,7 +343,7 @@ public class ConcurrentUtilsTest {
*/
@Test
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
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();
EasyMock.expect(init.get()).andReturn(result);
EasyMock.replay(init);
assertSame("Wrong result object", result, ConcurrentUtils
.initializeUnchecked(init));
assertSame(result, ConcurrentUtils.initializeUnchecked(init), "Wrong result object");
EasyMock.verify(init);
}
@ -393,7 +390,7 @@ public class ConcurrentUtilsTest {
ConcurrentUtils.initializeUnchecked(init);
fail("Exception not thrown!");
} catch (final ConcurrentRuntimeException crex) {
assertSame("Wrong cause", cause, crex.getCause());
assertSame(cause, crex.getCause(), "Wrong cause");
}
EasyMock.verify(init);
}
@ -445,9 +442,8 @@ public class ConcurrentUtilsTest {
final Integer value = 42;
final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<>();
map.put(key, value);
assertEquals("Wrong result", value,
ConcurrentUtils.putIfAbsent(map, key, 0));
assertEquals("Wrong value in map", value, map.get(key));
assertEquals(value, ConcurrentUtils.putIfAbsent(map, key, 0), "Wrong result");
assertEquals(value, map.get(key), "Wrong value in map");
}
/**
@ -458,9 +454,8 @@ public class ConcurrentUtilsTest {
final String key = "testKey";
final Integer value = 42;
final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<>();
assertEquals("Wrong result", value,
ConcurrentUtils.putIfAbsent(map, key, value));
assertEquals("Wrong value in map", value, map.get(key));
assertEquals(value, ConcurrentUtils.putIfAbsent(map, key, value), "Wrong result");
assertEquals(value, map.get(key), "Wrong value in map");
}
/**
@ -468,8 +463,7 @@ public class ConcurrentUtilsTest {
*/
@Test
public void testPutIfAbsentNullMap() {
assertNull("Wrong result",
ConcurrentUtils.putIfAbsent(null, "test", 100));
assertNull(ConcurrentUtils.putIfAbsent(null, "test", 100), "Wrong result");
}
/**
@ -488,9 +482,8 @@ public class ConcurrentUtilsTest {
final Integer value = 42;
final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<>();
map.put(key, value);
assertEquals("Wrong result", value,
ConcurrentUtils.createIfAbsent(map, key, init));
assertEquals("Wrong value in map", value, map.get(key));
assertEquals(value, ConcurrentUtils.createIfAbsent(map, key, init), "Wrong result");
assertEquals(value, map.get(key), "Wrong value in map");
EasyMock.verify(init);
}
@ -510,9 +503,8 @@ public class ConcurrentUtilsTest {
EasyMock.expect(init.get()).andReturn(value);
EasyMock.replay(init);
final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<>();
assertEquals("Wrong result", value,
ConcurrentUtils.createIfAbsent(map, key, init));
assertEquals("Wrong value in map", value, map.get(key));
assertEquals(value, ConcurrentUtils.createIfAbsent(map, key, init), "Wrong result");
assertEquals(value, map.get(key), "Wrong value in map");
EasyMock.verify(init);
}
@ -528,8 +520,7 @@ public class ConcurrentUtilsTest {
ConcurrentInitializer<Integer> init = EasyMock
.createMock(ConcurrentInitializer.class);
EasyMock.replay(init);
assertNull("Wrong result",
ConcurrentUtils.createIfAbsent(null, "test", init));
assertNull(ConcurrentUtils.createIfAbsent(null, "test", init), "Wrong result");
EasyMock.verify(init);
}
@ -544,9 +535,8 @@ public class ConcurrentUtilsTest {
final String key = "testKey";
final Integer value = 42;
map.put(key, value);
assertNull("Wrong result",
ConcurrentUtils.createIfAbsent(map, key, null));
assertEquals("Map was changed", value, map.get(key));
assertNull(ConcurrentUtils.createIfAbsent(map, key, null), "Wrong result");
assertEquals(value, map.get(key), "Map was changed");
}
/**
@ -557,10 +547,9 @@ public class ConcurrentUtilsTest {
final String key = "testKey";
final Integer value = 42;
final ConcurrentMap<String, Integer> map = new ConcurrentHashMap<>();
assertEquals("Wrong result", value,
ConcurrentUtils.createIfAbsentUnchecked(map, key,
new ConstantInitializer<>(value)));
assertEquals("Wrong value in map", value, map.get(key));
assertEquals(value, ConcurrentUtils.createIfAbsentUnchecked(map, key, new ConstantInitializer<>(value)),
"Wrong result");
assertEquals(value, map.get(key), "Wrong value in map");
}
/**
@ -583,7 +572,7 @@ public class ConcurrentUtilsTest {
new ConcurrentHashMap<>(), "test", init);
fail("Exception not thrown!");
} catch (final ConcurrentRuntimeException crex) {
assertEquals("Wrong cause", ex, crex.getCause());
assertEquals(ex, crex.getCause(), "Wrong cause");
}
EasyMock.verify(init);
}

View File

@ -16,13 +16,13 @@
*/
package org.apache.commons.lang3.concurrent;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.regex.Pattern;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Test class for {@code ConstantInitializer}.
@ -34,7 +34,7 @@ public class ConstantInitializerTest {
/** The initializer to be tested. */
private ConstantInitializer<Integer> init;
@Before
@BeforeEach
public void setUp() throws Exception {
init = new ConstantInitializer<>(VALUE);
}
@ -46,12 +46,11 @@ public class ConstantInitializerTest {
* @param expected the expected result
*/
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) {
assertTrue("Not symmetric", expected == obj.equals(init));
assertTrue(expected == obj.equals(init), "Not symmetric");
if (expected) {
assertEquals("Different hash codes", init.hashCode(),
obj.hashCode());
assertEquals(init.hashCode(), obj.hashCode(), "Different hash codes");
}
}
}
@ -61,7 +60,7 @@ public class ConstantInitializerTest {
*/
@Test
public void testGetObject() {
assertEquals("Wrong object", VALUE, init.getObject());
assertEquals(VALUE, init.getObject(), "Wrong object");
}
/**
@ -71,7 +70,7 @@ public class ConstantInitializerTest {
*/
@Test
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
.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
public void testToStringNull() {
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;
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
@ -29,7 +29,7 @@ import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* Test class for {@code EventCountCircuitBreaker}.
@ -51,9 +51,8 @@ public class EventCountCircuitBreakerTest {
public void testIntervalCalculation() {
final EventCountCircuitBreaker breaker = new EventCountCircuitBreaker(OPENING_THRESHOLD, 1,
TimeUnit.SECONDS, CLOSING_THRESHOLD, 2, TimeUnit.MILLISECONDS);
assertEquals("Wrong opening interval", NANO_FACTOR, breaker.getOpeningInterval());
assertEquals("Wrong closing interval", 2 * NANO_FACTOR / 1000,
breaker.getClosingInterval());
assertEquals(NANO_FACTOR, breaker.getOpeningInterval(), "Wrong opening interval");
assertEquals(2 * NANO_FACTOR / 1000, breaker.getClosingInterval(), "Wrong closing interval");
}
/**
@ -64,7 +63,7 @@ public class EventCountCircuitBreakerTest {
public void testDefaultClosingInterval() {
final EventCountCircuitBreaker breaker = new EventCountCircuitBreaker(OPENING_THRESHOLD, 1,
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() {
final EventCountCircuitBreaker breaker = new EventCountCircuitBreaker(OPENING_THRESHOLD, 1,
TimeUnit.SECONDS);
assertEquals("Wrong closing interval", NANO_FACTOR, breaker.getClosingInterval());
assertEquals("Wrong closing threshold", OPENING_THRESHOLD,
breaker.getClosingThreshold());
assertEquals(NANO_FACTOR, breaker.getClosingInterval(), "Wrong closing interval");
assertEquals(OPENING_THRESHOLD, breaker.getClosingThreshold(), "Wrong closing threshold");
}
/**
@ -87,8 +85,8 @@ public class EventCountCircuitBreakerTest {
public void testInitiallyClosed() {
final EventCountCircuitBreaker breaker = new EventCountCircuitBreaker(OPENING_THRESHOLD, 1,
TimeUnit.SECONDS);
assertFalse("Open", breaker.isOpen());
assertTrue("Not closed", breaker.isClosed());
assertFalse(breaker.isOpen(), "Open");
assertTrue(breaker.isClosed(), "Not closed");
}
/**
@ -100,7 +98,7 @@ public class EventCountCircuitBreakerTest {
TimeUnit.SECONDS);
final long now = breaker.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,
TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS);
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++;
}
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,
TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS);
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;
}
assertTrue("Not closed", breaker.isClosed());
assertTrue(breaker.isClosed(), "Not closed");
}
/**
@ -150,8 +148,8 @@ public class EventCountCircuitBreakerTest {
open = !breaker.at(startTime).incrementAndCheckState();
startTime += timeIncrement;
}
assertTrue("Not open", open);
assertFalse("Closed", breaker.isClosed());
assertTrue(open, "Not open");
assertFalse(breaker.isClosed(), "Closed");
}
/**
@ -165,8 +163,8 @@ public class EventCountCircuitBreakerTest {
TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS);
long startTime = timeIncrement * (OPENING_THRESHOLD + 1);
boolean open = !breaker.at(startTime).incrementAndCheckState(OPENING_THRESHOLD + 1);
assertTrue("Not open", open);
assertFalse("Closed", breaker.isClosed());
assertTrue(open, "Not open");
assertFalse(breaker.isClosed(), "Closed");
}
/**
@ -180,12 +178,11 @@ public class EventCountCircuitBreakerTest {
long startTime = 0;
breaker.open();
for (int i = 0; i <= CLOSING_THRESHOLD; i++) {
assertFalse("Not open", breaker.at(startTime).incrementAndCheckState());
assertFalse(breaker.at(startTime).incrementAndCheckState(), "Not open");
startTime += 1000;
}
assertFalse("Closed in new interval", breaker.at(startTime + NANO_FACTOR)
.incrementAndCheckState());
assertTrue("Not open at end", breaker.isOpen());
assertFalse(breaker.at(startTime + NANO_FACTOR).incrementAndCheckState(), "Closed in new interval");
assertTrue(breaker.isOpen(), "Not open at end");
}
/**
@ -198,11 +195,10 @@ public class EventCountCircuitBreakerTest {
10, TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS);
breaker.open();
breaker.at(1000).incrementAndCheckState();
assertFalse("Already closed", breaker.at(2000).checkState());
assertFalse("Closed at interval end", breaker.at(NANO_FACTOR).checkState());
assertTrue("Not closed after interval end", breaker.at(NANO_FACTOR + 1)
.checkState());
assertTrue("Not closed at end", breaker.isClosed());
assertFalse(breaker.at(2000).checkState(), "Already closed");
assertFalse(breaker.at(NANO_FACTOR).checkState(), "Closed at interval end");
assertTrue(breaker.at(NANO_FACTOR + 1).checkState(), "Not closed after interval end");
assertTrue(breaker.isClosed(), "Not closed at end");
}
/**
@ -214,8 +210,8 @@ public class EventCountCircuitBreakerTest {
final EventCountCircuitBreakerTestImpl breaker = new EventCountCircuitBreakerTestImpl(OPENING_THRESHOLD, 2,
TimeUnit.SECONDS, CLOSING_THRESHOLD, 1, TimeUnit.SECONDS);
breaker.at(NANO_FACTOR - 1000).open();
assertTrue("Not open", breaker.isOpen());
assertFalse("Already closed", breaker.at(NANO_FACTOR + 100).checkState());
assertTrue(breaker.isOpen(), "Not open");
assertFalse(breaker.at(NANO_FACTOR + 100).checkState(), "Already closed");
}
/**
@ -230,11 +226,11 @@ public class EventCountCircuitBreakerTest {
for (int i = 0; i <= OPENING_THRESHOLD; i++) {
breaker.at(time++).incrementAndCheckState();
}
assertTrue("Not open", breaker.isOpen());
assertTrue(breaker.isOpen(), "Not open");
time += NANO_FACTOR - 1000;
assertFalse("Already closed", breaker.at(time).incrementAndCheckState());
assertFalse(breaker.at(time).incrementAndCheckState(), "Already closed");
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) {
breaker.at(time).incrementAndCheckState();
}
assertTrue("Not open", breaker.isOpen());
assertTrue(breaker.isOpen(), "Not open");
breaker.close();
assertTrue("Not closed", breaker.isClosed());
assertTrue("Open again", breaker.at(time + 1000).incrementAndCheckState());
assertTrue(breaker.isClosed(), "Not closed");
assertTrue(breaker.at(time + 1000).incrementAndCheckState(), "Open again");
}
/**
@ -396,11 +392,11 @@ public class EventCountCircuitBreakerTest {
@Override
public void propertyChange(final PropertyChangeEvent evt) {
assertEquals("Wrong event source", expectedSource, evt.getSource());
assertEquals("Wrong property name", "open", evt.getPropertyName());
assertEquals(expectedSource, evt.getSource(), "Wrong event source");
assertEquals("open", evt.getPropertyName(), "Wrong property name");
final Boolean newValue = (Boolean) evt.getNewValue();
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);
}

View File

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

View File

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

View File

@ -16,11 +16,12 @@
*/
package org.apache.commons.lang3.concurrent;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.Iterator;
import java.util.NoSuchElementException;
@ -28,8 +29,8 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.junit.Before;
import org.junit.Test;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
/**
* Test class for {@link MultiBackgroundInitializer}.
@ -41,7 +42,7 @@ public class MultiBackgroundInitializerTest {
/** The initializer to be tested. */
private MultiBackgroundInitializer initializer;
@Before
@BeforeEach
public void setUp() throws Exception {
initializer = new MultiBackgroundInitializer();
}
@ -59,11 +60,10 @@ public class MultiBackgroundInitializerTest {
final ExecutorService expExec) throws ConcurrentException {
final ChildBackgroundInitializer cinit = (ChildBackgroundInitializer) child;
final Integer result = cinit.get();
assertEquals("Wrong result", 1, result.intValue());
assertEquals("Wrong number of executions", 1, cinit.initializeCalls);
assertEquals(1, result.intValue(), "Wrong result");
assertEquals(1, cinit.initializeCalls, "Wrong number of executions");
if (expExec != null) {
assertEquals("Wrong executor service", expExec,
cinit.currentExecutor);
assertEquals(expExec, cinit.currentExecutor, "Wrong executor service");
}
}
@ -71,18 +71,18 @@ public class MultiBackgroundInitializerTest {
* Tests addInitializer() if a null name is passed in. This should cause an
* exception.
*/
@Test(expected = IllegalArgumentException.class)
@Test
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
* cause an exception.
*/
@Test(expected = IllegalArgumentException.class)
@Test
public void testAddInitializerNullInit() {
initializer.addInitializer(CHILD_INIT, null);
assertThrows(IllegalArgumentException.class, () -> initializer.addInitializer(CHILD_INIT, null));
}
/**
@ -92,12 +92,11 @@ public class MultiBackgroundInitializerTest {
*/
@Test
public void testInitializeNoChildren() throws ConcurrentException {
assertTrue("Wrong result of start()", initializer.start());
assertTrue(initializer.start(), "Wrong result of start()");
final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer
.get();
assertTrue("Got child initializers", res.initializerNames().isEmpty());
assertTrue("Executor not shutdown", initializer.getActiveExecutor()
.isShutdown());
assertTrue(res.initializerNames().isEmpty(), "Got child initializers");
assertTrue(initializer.getActiveExecutor().isShutdown(), "Executor not shutdown");
}
/**
@ -118,16 +117,13 @@ public class MultiBackgroundInitializerTest {
initializer.start();
final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer
.get();
assertEquals("Wrong number of child initializers", count, res
.initializerNames().size());
assertEquals(count, res.initializerNames().size(), "Wrong number of child initializers");
for (int i = 0; i < count; i++) {
final String key = CHILD_INIT + i;
assertTrue("Name not found: " + key, res.initializerNames()
.contains(key));
assertEquals("Wrong result object", Integer.valueOf(1), res
.getResultObject(key));
assertFalse("Exception flag", res.isException(key));
assertNull("Got an exception", res.getException(key));
assertTrue(res.initializerNames().contains(key), "Name not found: " + key);
assertEquals(Integer.valueOf(1), res.getResultObject(key), "Wrong result object");
assertFalse(res.isException(key), "Exception flag");
assertNull(res.getException(key), "Got an exception");
checkChild(res.getInitializer(key), initializer.getActiveExecutor());
}
return res;
@ -141,8 +137,7 @@ public class MultiBackgroundInitializerTest {
@Test
public void testInitializeTempExec() throws ConcurrentException {
checkInitialize();
assertTrue("Executor not shutdown", initializer.getActiveExecutor()
.isShutdown());
assertTrue(initializer.getActiveExecutor().isShutdown(), "Executor not shutdown");
}
/**
@ -156,9 +151,8 @@ public class MultiBackgroundInitializerTest {
try {
initializer = new MultiBackgroundInitializer(exec);
checkInitialize();
assertEquals("Wrong executor", exec, initializer
.getActiveExecutor());
assertFalse("Executor was shutdown", exec.isShutdown());
assertEquals(exec, initializer.getActiveExecutor(), "Wrong executor");
assertFalse(exec.isShutdown(), "Executor was shutdown");
} finally {
exec.shutdown();
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
*/
@Test(expected = NoSuchElementException.class)
@Test
public void testResultGetInitializerUnknown() throws ConcurrentException {
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
*/
@Test(expected = NoSuchElementException.class)
@Test
public void testResultGetResultObjectUnknown() throws ConcurrentException {
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
*/
@Test(expected = NoSuchElementException.class)
@Test
public void testResultGetExceptionUnknown() throws ConcurrentException {
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
*/
@Test(expected = NoSuchElementException.class)
@Test
public void testResultIsExceptionUnknown() throws ConcurrentException {
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
*/
@Test(expected = UnsupportedOperationException.class)
@Test
public void testResultInitializerNamesModify() throws ConcurrentException {
checkInitialize();
final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer
.get();
final Iterator<String> it = res.initializerNames().iterator();
it.next();
it.remove();
assertThrows(UnsupportedOperationException.class, it::remove);
}
/**
@ -286,7 +280,7 @@ public class MultiBackgroundInitializerTest {
initializer.get();
fail("Runtime exception not thrown!");
} 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();
final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer
.get();
assertTrue("No exception flag", res.isException(CHILD_INIT));
assertNull("Got a results object", res.getResultObject(CHILD_INIT));
assertTrue(res.isException(CHILD_INIT), "No exception flag");
assertNull(res.getResultObject(CHILD_INIT), "Got a results object");
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();
final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer
.get();
assertTrue("Wrong success flag", res.isSuccessful());
assertTrue(res.isSuccessful(), "Wrong success flag");
}
/**
@ -342,7 +336,7 @@ public class MultiBackgroundInitializerTest {
initializer.start();
final MultiBackgroundInitializer.MultiBackgroundInitializerResults res = initializer
.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);
final MultiBackgroundInitializer.MultiBackgroundInitializerResults res2 = (MultiBackgroundInitializer.MultiBackgroundInitializerResults) res
.getResultObject(nameMulti);
assertEquals("Wrong number of initializers", count, res2
.initializerNames().size());
assertEquals(count, res2.initializerNames().size(), "Wrong number of initializers");
for (int i = 0; i < count; i++) {
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;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* Test class for {@code ThresholdCircuitBreaker}.
@ -41,7 +41,7 @@ public class ThresholdCircuitBreakerTest {
public void testThreshold() {
final ThresholdCircuitBreaker circuit = new ThresholdCircuitBreaker(threshold);
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() {
final ThresholdCircuitBreaker circuit = new ThresholdCircuitBreaker(threshold);
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
public void testThresholdEqualsZero() {
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.close();
// 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
public void testGettingThreshold() {
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;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
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.ScheduledExecutorService;
@ -29,7 +30,7 @@ import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.easymock.EasyMock;
import org.junit.Test;
import org.junit.jupiter.api.Test;
/**
* Test class for TimedSemaphore.
@ -55,24 +56,22 @@ public class TimedSemaphoreTest {
final TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD, UNIT,
LIMIT);
EasyMock.verify(service);
assertEquals("Wrong service", service, semaphore.getExecutorService());
assertEquals("Wrong period", PERIOD, semaphore.getPeriod());
assertEquals("Wrong unit", UNIT, semaphore.getUnit());
assertEquals("Statistic available", 0, semaphore
.getLastAcquiresPerPeriod());
assertEquals("Average available", 0.0, semaphore
.getAverageCallsPerPeriod(), .05);
assertFalse("Already shutdown", semaphore.isShutdown());
assertEquals("Wrong limit", LIMIT, semaphore.getLimit());
assertEquals(service, semaphore.getExecutorService(), "Wrong service");
assertEquals(PERIOD, semaphore.getPeriod(), "Wrong period");
assertEquals(UNIT, semaphore.getUnit(), "Wrong unit");
assertEquals(0, semaphore.getLastAcquiresPerPeriod(), "Statistic available");
assertEquals(0.0, semaphore.getAverageCallsPerPeriod(), .05, "Average available");
assertFalse(semaphore.isShutdown(), "Already shutdown");
assertEquals(LIMIT, semaphore.getLimit(), "Wrong limit");
}
/**
* Tries to create an instance with a negative period. This should cause an
* exception.
*/
@Test(expected = IllegalArgumentException.class)
@Test
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 ScheduledThreadPoolExecutor exec = (ScheduledThreadPoolExecutor) semaphore
.getExecutorService();
assertFalse("Wrong periodic task policy", exec
.getContinueExistingPeriodicTasksAfterShutdownPolicy());
assertFalse("Wrong delayed task policy", exec
.getExecuteExistingDelayedTasksAfterShutdownPolicy());
assertFalse("Already shutdown", exec.isShutdown());
assertFalse(exec.getContinueExistingPeriodicTasksAfterShutdownPolicy(), "Wrong periodic task policy");
assertFalse(exec.getExecuteExistingDelayedTasksAfterShutdownPolicy(), "Wrong delayed task policy");
assertFalse(exec.isShutdown(), "Already shutdown");
semaphore.shutdown();
}
@ -102,7 +99,7 @@ public class TimedSemaphoreTest {
final TimedSemaphoreTestImpl semaphore = new TimedSemaphoreTestImpl(PERIOD,
UNIT, LIMIT);
final ScheduledFuture<?> future = semaphore.startTimer();
assertNotNull("No future returned", future);
assertNotNull(future, "No future returned");
Thread.sleep(PERIOD);
final int trials = 10;
int count = 0;
@ -123,9 +120,8 @@ public class TimedSemaphoreTest {
public void testShutdownOwnExecutor() {
final TimedSemaphore semaphore = new TimedSemaphore(PERIOD, UNIT, LIMIT);
semaphore.shutdown();
assertTrue("Not shutdown", semaphore.isShutdown());
assertTrue("Executor not shutdown", semaphore.getExecutorService()
.isShutdown());
assertTrue(semaphore.isShutdown(), "Not shutdown");
assertTrue(semaphore.getExecutorService().isShutdown(), "Executor not shutdown");
}
/**
@ -140,7 +136,7 @@ public class TimedSemaphoreTest {
final TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD, UNIT,
LIMIT);
semaphore.shutdown();
assertTrue("Not shutdown", semaphore.isShutdown());
assertTrue(semaphore.isShutdown(), "Not shutdown");
EasyMock.verify(service);
}
@ -175,7 +171,7 @@ public class TimedSemaphoreTest {
PERIOD, UNIT, LIMIT);
semaphore.acquire();
semaphore.shutdown();
assertTrue("Not shutdown", semaphore.isShutdown());
assertTrue(semaphore.isShutdown(), "Not shutdown");
EasyMock.verify(service, future);
}
@ -224,16 +220,13 @@ public class TimedSemaphoreTest {
t.start();
latch.await();
// now the semaphore's limit should be reached and the thread blocked
assertEquals("Wrong semaphore count", count - 1, semaphore
.getAcquireCount());
assertEquals(count - 1, semaphore.getAcquireCount(), "Wrong semaphore count");
// this wakes up the thread, it should call the semaphore once more
semaphore.endOfPeriod();
t.join();
assertEquals("Wrong semaphore count (2)", 1, semaphore
.getAcquireCount());
assertEquals("Wrong acquire() count", count - 1, semaphore
.getLastAcquiresPerPeriod());
assertEquals(1, semaphore.getAcquireCount(), "Wrong semaphore count (2)");
assertEquals(count - 1, semaphore.getLastAcquiresPerPeriod(), "Wrong acquire() count");
EasyMock.verify(service, future);
}
@ -263,11 +256,10 @@ public class TimedSemaphoreTest {
}
for (int i = 0; i < count; i++) {
semaphore.latch.await();
assertEquals("Wrong count", 1, semaphore.getAcquireCount());
assertEquals(1, semaphore.getAcquireCount(), "Wrong count");
semaphore.latch = new CountDownLatch(1);
semaphore.endOfPeriod();
assertEquals("Wrong acquire count", 1, semaphore
.getLastAcquiresPerPeriod());
assertEquals(1, semaphore.getLastAcquiresPerPeriod(), "Wrong acquire count");
}
for (int i = 0; i < count; i++) {
threads[i].join();
@ -304,11 +296,11 @@ public class TimedSemaphoreTest {
*
* @throws java.lang.InterruptedException so we don't have to catch it
*/
@Test(expected = IllegalStateException.class)
@Test
public void testPassAfterShutdown() throws InterruptedException {
final TimedSemaphore semaphore = new TimedSemaphore(PERIOD, UNIT, LIMIT);
semaphore.shutdown();
semaphore.acquire();
assertThrows(IllegalStateException.class, semaphore::acquire);
}
/**
@ -330,7 +322,7 @@ public class TimedSemaphoreTest {
t.start();
latch.await();
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);
semaphore.acquire();
semaphore.endOfPeriod();
assertEquals("Wrong average (1)", 1.0, semaphore
.getAverageCallsPerPeriod(), .005);
assertEquals(1.0, semaphore.getAverageCallsPerPeriod(), .005, "Wrong average (1)");
semaphore.acquire();
semaphore.acquire();
semaphore.endOfPeriod();
assertEquals("Wrong average (2)", 1.5, semaphore
.getAverageCallsPerPeriod(), .005);
assertEquals(1.5, semaphore.getAverageCallsPerPeriod(), .005, "Wrong average (2)");
EasyMock.verify(service, future);
}
@ -374,13 +364,11 @@ public class TimedSemaphoreTest {
final TimedSemaphore semaphore = new TimedSemaphore(service, PERIOD, UNIT,
LIMIT);
for (int i = 0; i < LIMIT; i++) {
assertEquals("Wrong available count at " + i, LIMIT - i, semaphore
.getAvailablePermits());
assertEquals(LIMIT - i, semaphore.getAvailablePermits(), "Wrong available count at " + i);
semaphore.acquire();
}
semaphore.endOfPeriod();
assertEquals("Wrong available count in new period", LIMIT, semaphore
.getAvailablePermits());
assertEquals(LIMIT, semaphore.getAvailablePermits(), "Wrong available count in new period");
EasyMock.verify(service, future);
}
@ -407,17 +395,17 @@ public class TimedSemaphoreTest {
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.
*/
@Test(expected = IllegalStateException.class)
@Test
public void testTryAcquireAfterShutdown() {
final TimedSemaphore semaphore = new TimedSemaphore(PERIOD, UNIT, LIMIT);
semaphore.shutdown();
semaphore.tryAcquire();
assertThrows(IllegalStateException.class, semaphore::tryAcquire);
}
/**