Skip to content

Commit

Permalink
Use MockitoExtension and @mock annotation
Browse files Browse the repository at this point in the history
This enables mock usage validation by Mockito.
  • Loading branch information
runeflobakk committed Sep 26, 2024
1 parent ba2f5fe commit 0574ad5
Show file tree
Hide file tree
Showing 7 changed files with 68 additions and 67 deletions.
34 changes: 14 additions & 20 deletions src/test/java/no/digipost/DiggBaseTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,6 @@
import static org.junit.jupiter.api.Assertions.fail;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
Expand Down Expand Up @@ -148,12 +147,12 @@ public void objectManagedByAutoCloseIsSameInstanceAsGiven() {
}


interface MyResource {
void done();
}

@Test
public void useArbitraryObjectWithTryWithResources() {
abstract class MyResource {
abstract void done();
}
MyResource resource = mock(MyResource.class);
public void useArbitraryObjectWithTryWithResources(@Mock MyResource resource) {
try (ThrowingAutoClosed<MyResource, RuntimeException> managedResource = throwingAutoClose(resource, MyResource::done)) {
verifyNoInteractions(resource);
managedResource.object(); //just to avoid javac lint warning
Expand All @@ -162,14 +161,14 @@ abstract class MyResource {
verifyNoMoreInteractions(resource);
}


interface MyAutoCloseableResource extends AutoCloseable {
void done() throws IOException;
}

@Test
public void wrappingAnAlreadyAutoCloseableWithAutoCloseWillAlsoInvokeClose() throws Exception {
abstract class MyResource implements AutoCloseable {
abstract void done() throws IOException;
@Override public abstract void close() throws IOException;
}
MyResource resource = mock(MyResource.class);
try (ThrowingAutoClosed<MyResource, IOException> managedResource = throwingAutoClose(resource, MyResource::done)) {
public void wrappingAnAlreadyAutoCloseableWithAutoCloseWillAlsoInvokeClose(@Mock MyAutoCloseableResource resource) throws Exception {
try (ThrowingAutoClosed<MyAutoCloseableResource, IOException> managedResource = throwingAutoClose(resource, MyAutoCloseableResource::done)) {
verifyNoInteractions(resource);
managedResource.object(); //just to avoid javac lint warning
}
Expand All @@ -180,11 +179,7 @@ abstract class MyResource implements AutoCloseable {
}

@Test
public void autoCloseWithoutCheckedException() {
abstract class MyResource {
abstract void done();
}
MyResource resource = mock(MyResource.class);
public void autoCloseWithoutCheckedException(@Mock MyResource resource) {
try (AutoClosed<MyResource> managedResource = autoClose(resource, MyResource::done)) {
verifyNoInteractions(resource);
managedResource.object(); //just to avoid javac lint warning
Expand All @@ -194,8 +189,7 @@ abstract class MyResource {
}

@Test
public void getAllExceptionsFromClosingSeveralAutoCloseables() throws Exception {
AutoCloseable closeable = mock(AutoCloseable.class);
public void getAllExceptionsFromClosingSeveralAutoCloseables(@Mock AutoCloseable closeable) throws Exception {
doNothing()
.doThrow(new IOException())
.doNothing()
Expand Down
35 changes: 18 additions & 17 deletions src/test/java/no/digipost/DiggCollectorsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@
import no.digipost.tuple.ViewableAsTuple;
import no.digipost.util.ViewableAsOptional;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.quicktheories.core.Gen;
import uk.co.probablyfine.matchers.OptionalMatchers;

Expand Down Expand Up @@ -53,20 +56,20 @@
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.quicktheories.QuickTheory.qt;
import static org.quicktheories.generators.SourceDSL.lists;
import static org.quicktheories.generators.SourceDSL.strings;
import static uk.co.probablyfine.matchers.Java8Matchers.where;
import static uk.co.probablyfine.matchers.Java8Matchers.whereNot;
import static uk.co.probablyfine.matchers.OptionalMatchers.contains;

public class DiggCollectorsTest {
@ExtendWith(MockitoExtension.class)
class DiggCollectorsTest {

interface NumTranslation extends ViewableAsTuple<Integer, Optional<String>> {}

@Test
public void collectTuplesIntoMap() {
void collectTuplesIntoMap() {
NumTranslation oneInEnglish = () -> Tuple.of(1, Optional.of("one"));
NumTranslation twoInEnglish = () -> Tuple.of(2, Optional.of("two"));
NumTranslation twoInSpanish = () -> Tuple.of(2, Optional.of("dos"));
Expand All @@ -83,7 +86,7 @@ public void collectTuplesIntoMap() {
}

@Test
public void collectMultitupleFromTuplesWithEqualFirstElement() {
void collectMultitupleFromTuplesWithEqualFirstElement() {
NumTranslation oneInEnglish = () -> Tuple.of(1, Optional.of("one"));
NumTranslation oneInSpanish = () -> Tuple.of(1, Optional.of("uno"));
NumTranslation oneInEsperanto = () -> Tuple.of(1, Optional.of("unu"));
Expand All @@ -96,13 +99,13 @@ public void collectMultitupleFromTuplesWithEqualFirstElement() {
}

@Test
public void collectNoTuplesYieldsEmptyOptional() {
void collectNoTuplesYieldsEmptyOptional() {
Optional<Tuple<Integer, List<String>>> noTuple = Stream.<Tuple<Integer, Optional<String>>>empty().collect(toMultituple());
assertThat(noTuple, OptionalMatchers.empty());
}

@Test
public void collectMultitupleFromTuplesWithNonDistinctFirstElementIsErroneous() {
void collectMultitupleFromTuplesWithNonDistinctFirstElementIsErroneous() {
NumTranslation oneInEnglish = () -> Tuple.of(1, Optional.of("one"));
NumTranslation missingOne = () -> Tuple.of(1, Optional.empty());
NumTranslation oneInEsperanto = () -> Tuple.of(1, Optional.of("unu"));
Expand All @@ -113,20 +116,20 @@ public void collectMultitupleFromTuplesWithNonDistinctFirstElementIsErroneous()
}

@Test
public void collectTheValueOfSingleElementStream() {
void collectTheValueOfSingleElementStream() {
assertThat(Stream.of(42).collect(allowAtMostOne()), contains(is(42)));
assertThat(Stream.empty().collect(allowAtMostOne()), OptionalMatchers.empty());
assertThat(Stream.of((String) null).collect(allowAtMostOne()), OptionalMatchers.empty());
}

@Test
public void allowAtMostOneFailsEvenIfExcessiveElementsAreNull() {
void allowAtMostOneFailsEvenIfExcessiveElementsAreNull() {
Stream<String> xAndNull = Stream.of("x", null);
assertThrows(ViewableAsOptional.TooManyElements.class, () -> xAndNull.collect(allowAtMostOne()));
}

@Test
public void convertTwoExceptionsToSingleWithSuppressed() {
void convertTwoExceptionsToSingleWithSuppressed() {
Exception mainException = new Exception("main");
Exception suppressedException = new Exception("suppressed");
Exception collatedException = Stream.of(mainException, suppressedException).collect(toSingleExceptionWithSuppressed()).get();
Expand All @@ -135,25 +138,23 @@ public void convertTwoExceptionsToSingleWithSuppressed() {
}

@Test
public void convertLotsOfExceptionsToSingleWithTheRestSuppressed() {
void convertLotsOfExceptionsToSingleWithTheRestSuppressed() {
Stream<Exception> exceptions = range(0, 300).mapToObj(n -> new Exception("exception-" + n));
Exception collatedException = exceptions.parallel().collect(toSingleExceptionWithSuppressed()).get();
assertThat(collatedException, where(Throwable::getSuppressed, arrayWithSize(299)));
assertThat(asList(collatedException.getSuppressed()), everyItem(where(Throwable::getSuppressed, emptyArray())));
}

@Test
public void addLotsOfSuppressedToGivenException() {
void addLotsOfSuppressedToGivenException() {
Stream<Exception> exceptions = range(0, 300).mapToObj(n -> new Exception("exception-" + n));
IOException collatedException = exceptions.parallel().collect(asSuppressedExceptionsOf(new IOException()));
assertThat(collatedException, where(Throwable::getSuppressed, arrayWithSize(300)));
assertThat(asList(collatedException.getSuppressed()), everyItem(where(Throwable::getSuppressed, emptyArray())));
}

@Test
public void suppressesExceptionsCorrectlyWithTryCatchBlocks() throws SQLException {
Connection connection = mock(Connection.class);
PreparedStatement pstmt = mock(PreparedStatement.class);
void suppressesExceptionsCorrectlyWithTryCatchBlocks(@Mock Connection connection, @Mock PreparedStatement pstmt) throws SQLException {
SQLException connectionCloseException = new SQLException();
BatchUpdateException statementCloseException = new BatchUpdateException();
doThrow(connectionCloseException).when(connection).close();
Expand All @@ -170,7 +171,7 @@ public void suppressesExceptionsCorrectlyWithTryCatchBlocks() throws SQLExceptio
}

@Test
public void convertNoExceptionsToEmptyOptional() {
void convertNoExceptionsToEmptyOptional() {
Optional<Exception> noException = range(0, 300).parallel().mapToObj(n -> new Exception("exception-" + n)).filter(e -> false).collect(toSingleExceptionWithSuppressed());
assertThat(noException, whereNot(Optional::isPresent));
}
Expand All @@ -179,7 +180,7 @@ public void convertNoExceptionsToEmptyOptional() {
private final Gen<List<String>> listsWithAtLeastTwoElements = lists().of(strings().allPossible().ofLengthBetween(0, 10)).ofSizeBetween(2, 40);

@Test
public void allowAtMostOneFails() {
void allowAtMostOneFails() {
qt()
.forAll(listsWithAtLeastTwoElements)
.check(list -> {
Expand All @@ -193,7 +194,7 @@ public void allowAtMostOneFails() {
}

@Test
public void allowAtMostOneFailsWithCustomException() {
void allowAtMostOneFailsWithCustomException() {
IllegalStateException customException = new IllegalStateException();
qt()
.forAll(listsWithAtLeastTwoElements)
Expand Down
21 changes: 11 additions & 10 deletions src/test/java/no/digipost/DiggExceptionsTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
import no.digipost.concurrent.OneTimeToggle;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.io.IOException;
import java.io.UncheckedIOException;
Expand All @@ -42,25 +45,25 @@
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static uk.co.probablyfine.matchers.Java8Matchers.where;

public class DiggExceptionsTest {
@ExtendWith(MockitoExtension.class)
class DiggExceptionsTest {

@Test
public void causalChainOfNullIsEmptyStream() {
void causalChainOfNullIsEmptyStream() {
assertThat(causalChainOf(null).collect(toList()), empty());
}

@Test
public void returnsTheCausalChainOfExceptions() {
void returnsTheCausalChainOfExceptions() {
List<Throwable> exception = causalChainOf(new Exception(new IllegalStateException(new IOException()))).collect(toList());
assertThat(exception, contains(instanceOf(Exception.class), instanceOf(IllegalStateException.class), instanceOf(IOException.class)));
}

@Test
public void runAThrowingRunnableUnchecked() {
void runAThrowingRunnableUnchecked() {
OneTimeToggle toggled = new OneTimeToggle();
DiggExceptions.runUnchecked(() -> toggled.nowOrIfAlreadyThenThrow(() -> new AssertionError("should not be run twice!")));
assertThat(toggled, where(OneTimeToggle::yet));
Expand All @@ -70,15 +73,15 @@ public void runAThrowingRunnableUnchecked() {
}

@Test
public void getAThrowingSupplierUnchecked() {
void getAThrowingSupplierUnchecked() {
assertThat(getUnchecked(() -> 42), is(42));

Exception e = new Exception();
assertThat(assertThrows(RuntimeException.class, () -> getUnchecked(() -> { throw e; })), where(Exception::getCause, sameInstance(e)));
}

@Test
public void applyAThrowingFunctionUnchecked() {
void applyAThrowingFunctionUnchecked() {
assertThat(applyUnchecked(Math::round, 4.6f), is(5));
assertThat(applyUnchecked(n -> n, null), nullValue());
assertThat(applyUnchecked(n -> n, Optional.empty()), is(Optional.empty()));
Expand All @@ -88,14 +91,12 @@ public void applyAThrowingFunctionUnchecked() {
}

@Test
public void factoryMethodsForThrowingFunctionalInterfaces() throws Throwable {
void factoryMethodsForThrowingFunctionalInterfaces(@Mock Consumer<Exception> exceptionHandler) throws Throwable {
assertThat(mayThrow((t) -> t).apply("a"), is("a"));
assertThat(mayThrow((t, u) -> t).apply("a", "b"), is("a"));
assertThat(mayThrow(() -> "a").get(), is("a"));

Exception ex = new Exception();
@SuppressWarnings("unchecked")
Consumer<Exception> exceptionHandler = mock(Consumer.class);
mayThrow(t -> { if (t == null) throw ex; }).ifException(exceptionHandler).accept(null);
verify(exceptionHandler).accept(ex);

Expand Down
13 changes: 7 additions & 6 deletions src/test/java/no/digipost/DiggIOTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,27 +17,28 @@

import no.digipost.function.ThrowingConsumer;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.util.function.Consumer;

import static no.digipost.DiggIO.autoClosing;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

public class DiggIOTest {
@ExtendWith(MockitoExtension.class)
class DiggIOTest {

@Test
public void closesResourceAfterSuccess() throws Exception {
AutoCloseable resource = mock(AutoCloseable.class);
void closesResourceAfterSuccess(@Mock AutoCloseable resource) throws Exception {
autoClosing(r -> {}).accept(resource);
verify(resource, times(1)).close();
}

@Test
public void closesResourceAfterFailure() throws Exception {
AutoCloseable resource = mock(AutoCloseable.class);
void closesResourceAfterFailure(@Mock AutoCloseable resource) throws Exception {
Consumer<AutoCloseable> autoClosingConsumer = autoClosing((ThrowingConsumer<AutoCloseable, Exception>) r -> { throw new Exception(); });
assertThrows(RuntimeException.class, () -> autoClosingConsumer.accept(resource));
verify(resource, times(1)).close();
Expand Down
14 changes: 8 additions & 6 deletions src/test/java/no/digipost/function/ThrowingFunctionTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
package no.digipost.function;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.util.function.BiConsumer;
import java.util.function.Consumer;
Expand All @@ -26,10 +29,10 @@
import static org.hamcrest.Matchers.nullValue;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

@ExtendWith(MockitoExtension.class)
public class ThrowingFunctionTest {

private final RuntimeException ex = new RuntimeException("fail");
Expand All @@ -55,16 +58,15 @@ public void rethrowOriginalError() {
}

@Test
public void translateToEmptyOptionalAndDelegateExceptionToHandler() {
public void translateToEmptyOptionalAndDelegateExceptionToHandler(
@Mock Consumer<Exception> getException,
@Mock BiConsumer<Integer, Exception> getValueAndException) {

ThrowingFunction<Integer, ?, Exception> fn = i -> {throw ex;};

@SuppressWarnings("unchecked")
Consumer<Exception> getException = mock(Consumer.class);
assertThat(fn.ifException(getException).apply(42), is(empty()));
verify(getException, times(1)).accept(ex);

@SuppressWarnings("unchecked")
BiConsumer<Integer, Exception> getValueAndException = mock(BiConsumer.class);
assertThat(fn.ifException(getValueAndException).apply(42), is(empty()));
verify(getValueAndException, times(1)).accept(42, ex);
}
Expand Down
9 changes: 5 additions & 4 deletions src/test/java/no/digipost/function/ThrowingRunnableTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,16 +16,19 @@
package no.digipost.function;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.util.function.Consumer;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.sameInstance;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

@ExtendWith(MockitoExtension.class)
public class ThrowingRunnableTest {

private final RuntimeException ex = new RuntimeException();
Expand All @@ -45,10 +48,8 @@ public void rethrowOriginalError() {
}

@Test
public void translateToEmptyOptionalAndDelegateExceptionToHandler() {
public void translateToEmptyOptionalAndDelegateExceptionToHandler(@Mock Consumer<Exception> handler) {
ThrowingRunnable<Exception> fn = () -> {throw ex;};
@SuppressWarnings("unchecked")
Consumer<Exception> handler = mock(Consumer.class);

fn.ifException(handler).run();
verify(handler, times(1)).accept(ex);
Expand Down
Loading

0 comments on commit 0574ad5

Please sign in to comment.