diff --git a/src/test/java/org/concurrentmockito/ThreadsRunAllTestsHalfManualTest.java b/src/test/java/org/concurrentmockito/ThreadsRunAllTestsHalfManualTest.java index aa15ca4c20..3443c79c83 100644 --- a/src/test/java/org/concurrentmockito/ThreadsRunAllTestsHalfManualTest.java +++ b/src/test/java/org/concurrentmockito/ThreadsRunAllTestsHalfManualTest.java @@ -115,7 +115,7 @@ public void run() { DescriptiveMessagesWhenVerificationFailsTest.class, DescriptiveMessagesWhenTimesXVerificationFailsTest.class, BasicVerificationInOrderTest.class, - VerificationInOrderMixedWithOrdiraryVerificationTest.class, + VerificationInOrderMixedWithOrdinaryVerificationTest.class, DescriptiveMessagesOnVerificationInOrderErrorsTest.class, InvalidStateDetectionTest.class, ReplacingObjectMethodsTest.class, diff --git a/src/test/java/org/mockito/DescriptionTest.java b/src/test/java/org/mockito/DescriptionTest.java index 32565e4b6c..3f8306ad83 100644 --- a/src/test/java/org/mockito/DescriptionTest.java +++ b/src/test/java/org/mockito/DescriptionTest.java @@ -4,42 +4,50 @@ */ package org.mockito; -import static org.mockito.Mockito.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.description; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.exceptions.base.MockitoAssertionError; /** * Tests for https://github.com/mockito/mockito/issues/1712 */ public class DescriptionTest { - @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void verify_method_not_called_should_include_description_in_report() { final String description = "Failed to call doSomethingElse"; - expectedException.expect(MockitoAssertionError.class); - expectedException.expectMessage(description); Dependency dependency = spy(Dependency.class); SystemUnderTest systemUnderTest = new SystemUnderTest(); systemUnderTest.doNothing(dependency); - verify(dependency, description(description)).doSomethingElse(false); + + assertThatThrownBy( + () -> { + verify(dependency, description(description)).doSomethingElse(false); + }) + .isInstanceOf(MockitoAssertionError.class) + .hasMessageContaining(description); } @Test public void verify_method_called_with_unexpected_argument_should_include_description_in_report() { final String description = "Failed to call doSomethingElse with expected argument"; - expectedException.expect(MockitoAssertionError.class); - expectedException.expectMessage(description); Dependency dependency = spy(Dependency.class); SystemUnderTest systemUnderTest = new SystemUnderTest(); systemUnderTest.doSomething(dependency); - verify(dependency, description(description)).doSomethingElse(false); + + assertThatThrownBy( + () -> { + verify(dependency, description(description)).doSomethingElse(false); + }) + .isInstanceOf(MockitoAssertionError.class) + .hasMessageContaining(description); } static class SystemUnderTest { diff --git a/src/test/java/org/mockito/MockitoTest.java b/src/test/java/org/mockito/MockitoTest.java index 687ae4cd4b..8455011bb2 100644 --- a/src/test/java/org/mockito/MockitoTest.java +++ b/src/test/java/org/mockito/MockitoTest.java @@ -5,6 +5,7 @@ package org.mockito; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.times; import static org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress; @@ -28,56 +29,108 @@ public void shouldRemoveStubbableFromProgressAfterStubbing() { } @SuppressWarnings({"CheckReturnValue", "MockitoUsage"}) - @Test(expected = NotAMockException.class) + @Test public void shouldValidateMockWhenVerifying() { - Mockito.verify("notMock"); + assertThatThrownBy( + () -> { + Mockito.verify("notMock"); + }) + .isInstanceOf(NotAMockException.class) + .hasMessageContaining( + "Argument passed to verify() is of type String and is not a mock!") + .hasMessageContaining("Make sure you place the parenthesis correctly!"); } @SuppressWarnings({"CheckReturnValue", "MockitoUsage"}) - @Test(expected = NotAMockException.class) + @Test public void shouldValidateMockWhenVerifyingWithExpectedNumberOfInvocations() { - Mockito.verify("notMock", times(19)); + assertThatThrownBy( + () -> { + Mockito.verify("notMock", times(19)); + }) + .isInstanceOf(NotAMockException.class) + .hasMessageContaining( + "Argument passed to verify() is of type String and is not a mock!") + .hasMessageContaining("Make sure you place the parenthesis correctly!"); } - @Test(expected = NotAMockException.class) + @Test public void shouldValidateMockWhenVerifyingNoMoreInteractions() { - Mockito.verifyNoMoreInteractions("notMock"); + assertThatThrownBy( + () -> { + Mockito.verifyNoMoreInteractions("notMock"); + }) + .isInstanceOf(NotAMockException.class) + .hasMessageContaining("Argument(s) passed is not a mock!"); } - @Test(expected = NotAMockException.class) + @Test public void shouldValidateMockWhenVerifyingNoInteractions() { - Mockito.verifyNoInteractions("notMock"); + assertThatThrownBy( + () -> { + Mockito.verifyNoInteractions("notMock"); + }) + .isInstanceOf(NotAMockException.class) + .hasMessageContaining("Argument(s) passed is not a mock!"); } - @Test(expected = NullInsteadOfMockException.class) + @Test public void shouldValidateNullMockWhenVerifyingNoInteractions() { - Mockito.verifyNoInteractions(new Object[] {null}); + assertThatThrownBy( + () -> { + Mockito.verifyNoInteractions(new Object[] {null}); + }) + .isInstanceOf(NullInsteadOfMockException.class) + .hasMessageContaining("Argument(s) passed is null!"); } @SuppressWarnings({"CheckReturnValue", "MockitoUsage"}) - @Test(expected = NotAMockException.class) + @Test public void shouldValidateMockWhenCreatingInOrderObject() { - Mockito.inOrder("notMock"); + assertThatThrownBy( + () -> { + Mockito.inOrder("notMock"); + }) + .isInstanceOf(NotAMockException.class) + .hasMessageContaining("Argument(s) passed is not a mock!"); } @SuppressWarnings({"CheckReturnValue", "MockitoUsage"}) - @Test(expected = MockitoException.class) - public void shouldGiveExplantionOnStaticMockingWithoutInlineMockMaker() { - Mockito.mockStatic(Object.class); + @Test + public void shouldGiveExplanationOnStaticMockingWithoutInlineMockMaker() { + assertThatThrownBy( + () -> { + Mockito.mockStatic(Object.class); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "The used MockMaker SubclassByteBuddyMockMaker does not support the creation of static mocks", + "Mockito's inline mock maker supports static mocks based on the Instrumentation API.", + "You can simply enable this mock mode, by placing the 'mockito-inline' artifact where you are currently using 'mockito-core'.", + "Note that Mockito's inline mock maker is not supported on Android."); } @SuppressWarnings({"CheckReturnValue", "MockitoUsage"}) - @Test(expected = MockitoException.class) - public void shouldGiveExplantionOnConstructionMockingWithoutInlineMockMaker() { - Mockito.mockConstruction(Object.class); + @Test + public void shouldGiveExplanationOnConstructionMockingWithoutInlineMockMaker() { + assertThatThrownBy( + () -> { + Mockito.mockConstruction(Object.class); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "The used MockMaker SubclassByteBuddyMockMaker does not support the creation of construction mocks", + "Mockito's inline mock maker supports construction mocks based on the Instrumentation API.", + "You can simply enable this mock mode, by placing the 'mockito-inline' artifact where you are currently using 'mockito-core'.", + "Note that Mockito's inline mock maker is not supported on Android."); } @Test public void shouldStartingMockSettingsContainDefaultBehavior() { - // when + // given MockSettingsImpl settings = (MockSettingsImpl) Mockito.withSettings(); - // then - assertThat(Mockito.RETURNS_DEFAULTS).isEqualTo(settings.getDefaultAnswer()); + // when / then + assertThat(settings.getDefaultAnswer()).isEqualTo(Mockito.RETURNS_DEFAULTS); } } diff --git a/src/test/java/org/mockito/internal/configuration/MockAnnotationProcessorTest.java b/src/test/java/org/mockito/internal/configuration/MockAnnotationProcessorTest.java index 9c4ef88d88..b9e9dd0bb2 100644 --- a/src/test/java/org/mockito/internal/configuration/MockAnnotationProcessorTest.java +++ b/src/test/java/org/mockito/internal/configuration/MockAnnotationProcessorTest.java @@ -4,14 +4,15 @@ */ package org.mockito.internal.configuration; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + import java.util.List; import org.junit.Test; import org.mockito.MockedStatic; import org.mockito.exceptions.base.MockitoException; -import static org.assertj.core.api.Assertions.*; - public class MockAnnotationProcessorTest { @SuppressWarnings("unused") @@ -35,19 +36,34 @@ public void testNonGeneric() throws Exception { assertThat(type).isEqualTo(Void.class); } - @Test(expected = MockitoException.class) - public void testGeneric() throws Exception { - MockAnnotationProcessor.inferParameterizedType( - MockAnnotationProcessorTest.class.getDeclaredField("generic").getGenericType(), - "generic", - "Sample"); + @Test + public void testGeneric() { + assertThatThrownBy( + () -> { + MockAnnotationProcessor.inferParameterizedType( + MockAnnotationProcessorTest.class + .getDeclaredField("generic") + .getGenericType(), + "generic", + "Sample"); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining( + "Mockito cannot infer a static mock from a raw type for generic"); } - @Test(expected = MockitoException.class) - public void testRaw() throws Exception { - MockAnnotationProcessor.inferParameterizedType( - MockAnnotationProcessorTest.class.getDeclaredField("raw").getGenericType(), - "raw", - "Sample"); + @Test + public void testRaw() { + assertThatThrownBy( + () -> { + MockAnnotationProcessor.inferParameterizedType( + MockAnnotationProcessorTest.class + .getDeclaredField("raw") + .getGenericType(), + "raw", + "Sample"); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("Mockito cannot infer a static mock from a raw type for raw"); } } diff --git a/src/test/java/org/mockito/internal/configuration/MockInjectionTest.java b/src/test/java/org/mockito/internal/configuration/MockInjectionTest.java index 83012b299d..75f0b6e862 100644 --- a/src/test/java/org/mockito/internal/configuration/MockInjectionTest.java +++ b/src/test/java/org/mockito/internal/configuration/MockInjectionTest.java @@ -5,6 +5,7 @@ package org.mockito.internal.configuration; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import java.lang.reflect.Field; @@ -28,24 +29,44 @@ public void reset() throws Exception { withoutConstructor = null; } - @Test(expected = IllegalArgumentException.class) + @Test public void should_not_allow_null_on_field() { - MockInjection.onField((Field) null, this); + assertThatThrownBy( + () -> { + MockInjection.onField((Field) null, this); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("item in fields should not be null"); } - @Test(expected = IllegalArgumentException.class) + @Test public void should_not_allow_null_on_fields() { - MockInjection.onFields((Set) null, this); + assertThatThrownBy( + () -> { + MockInjection.onFields((Set) null, this); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("fields should not be null"); } - @Test(expected = IllegalArgumentException.class) - public void should_not_allow_null_on_instance_owning_the_field() throws Exception { - MockInjection.onField(field("withConstructor"), null); + @Test + public void should_not_allow_null_on_instance_owning_the_field() { + assertThatThrownBy( + () -> { + MockInjection.onField(field("withConstructor"), null); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("fieldOwner should not be null"); } - @Test(expected = IllegalArgumentException.class) - public void should_not_allow_null_on_mocks() throws Exception { - MockInjection.onField(field("withConstructor"), this).withMocks(null); + @Test + public void should_not_allow_null_on_mocks() { + assertThatThrownBy( + () -> { + MockInjection.onField(field("withConstructor"), this).withMocks(null); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("mocks should not be null"); } @Test @@ -55,7 +76,7 @@ public void can_try_constructor_injection() throws Exception { .tryConstructorInjection() .apply(); - assertThat(withConstructor.initializedWithConstructor).isEqualTo(true); + assertThat(withConstructor.initializedWithConstructor).isTrue(); } @Test diff --git a/src/test/java/org/mockito/internal/creation/MockSettingsImplTest.java b/src/test/java/org/mockito/internal/creation/MockSettingsImplTest.java index 2efbc50653..9e8d68d5d8 100644 --- a/src/test/java/org/mockito/internal/creation/MockSettingsImplTest.java +++ b/src/test/java/org/mockito/internal/creation/MockSettingsImplTest.java @@ -6,16 +6,11 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; import java.util.LinkedList; import java.util.List; import java.util.Set; -import org.assertj.core.api.Assertions; -import org.assertj.core.api.ThrowableAssert; import org.junit.Test; import org.mockito.Mock; import org.mockito.exceptions.base.MockitoException; @@ -31,34 +26,63 @@ public class MockSettingsImplTest extends TestBase { @Mock private InvocationListener invocationListener; @Mock private StubbingLookupListener stubbingLookupListener; - @Test(expected = MockitoException.class) + @Test @SuppressWarnings("unchecked") public void shouldNotAllowSettingNullInterface() { - mockSettingsImpl.extraInterfaces(List.class, null); + assertThatThrownBy( + () -> { + mockSettingsImpl.extraInterfaces(List.class, null); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("extraInterfaces() does not accept null parameters."); } - @Test(expected = MockitoException.class) + @Test @SuppressWarnings("unchecked") public void shouldNotAllowNonInterfaces() { - mockSettingsImpl.extraInterfaces(List.class, LinkedList.class); + assertThatThrownBy( + () -> { + mockSettingsImpl.extraInterfaces(List.class, LinkedList.class); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "extraInterfaces() accepts only interfaces", + "You passed following type: LinkedList which is not an interface."); } - @Test(expected = MockitoException.class) + @Test @SuppressWarnings("unchecked") public void shouldNotAllowUsingTheSameInterfaceAsExtra() { - mockSettingsImpl.extraInterfaces(List.class, LinkedList.class); + assertThatThrownBy( + () -> { + mockSettingsImpl.extraInterfaces(List.class, LinkedList.class); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "extraInterfaces() accepts only interfaces.", + "You passed following type: LinkedList which is not an interface."); } - @Test(expected = MockitoException.class) + @Test @SuppressWarnings("unchecked") public void shouldNotAllowEmptyExtraInterfaces() { - mockSettingsImpl.extraInterfaces(); + assertThatThrownBy( + () -> { + mockSettingsImpl.extraInterfaces(); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("extraInterfaces() requires at least one interface."); } - @Test(expected = MockitoException.class) + @Test @SuppressWarnings("unchecked") public void shouldNotAllowNullArrayOfExtraInterfaces() { - mockSettingsImpl.extraInterfaces((Class[]) null); + assertThatThrownBy( + () -> { + mockSettingsImpl.extraInterfaces((Class[]) null); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("extraInterfaces() requires at least one interface."); } @Test @@ -68,36 +92,36 @@ public void shouldAllowMultipleInterfaces() { mockSettingsImpl.extraInterfaces(List.class, Set.class); // then - assertEquals(2, mockSettingsImpl.getExtraInterfaces().size()); - assertTrue(mockSettingsImpl.getExtraInterfaces().contains(List.class)); - assertTrue(mockSettingsImpl.getExtraInterfaces().contains(Set.class)); + assertThat(mockSettingsImpl.getExtraInterfaces().size()).isEqualTo(2); + assertThat(mockSettingsImpl.getExtraInterfaces()).contains(List.class); + assertThat(mockSettingsImpl.getExtraInterfaces()).contains(Set.class); } @Test - public void shouldSetMockToBeSerializable() throws Exception { + public void shouldSetMockToBeSerializable() { // when mockSettingsImpl.serializable(); // then - assertTrue(mockSettingsImpl.isSerializable()); + assertThat(mockSettingsImpl.isSerializable()).isTrue(); } @Test - public void shouldKnowIfIsSerializable() throws Exception { + public void shouldKnowIfIsSerializable() { // given - assertFalse(mockSettingsImpl.isSerializable()); + assertThat(mockSettingsImpl.isSerializable()).isFalse(); // when mockSettingsImpl.serializable(); // then - assertTrue(mockSettingsImpl.isSerializable()); + assertThat(mockSettingsImpl.isSerializable()).isTrue(); } @Test public void shouldAddVerboseLoggingListener() { // given - assertFalse(mockSettingsImpl.hasInvocationListeners()); + assertThat(mockSettingsImpl.hasInvocationListeners()).isFalse(); // when mockSettingsImpl.verboseLogging(); @@ -111,34 +135,33 @@ public void shouldAddVerboseLoggingListener() { @Test public void shouldAddVerboseLoggingListenerOnlyOnce() { // given - assertFalse(mockSettingsImpl.hasInvocationListeners()); + assertThat(mockSettingsImpl.hasInvocationListeners()).isFalse(); // when mockSettingsImpl.verboseLogging().verboseLogging(); // then - Assertions.assertThat(mockSettingsImpl.getInvocationListeners()).hasSize(1); + assertThat(mockSettingsImpl.getInvocationListeners()).hasSize(1); } @Test @SuppressWarnings("unchecked") public void shouldAddInvocationListener() { // given - assertFalse(mockSettingsImpl.hasInvocationListeners()); + assertThat(mockSettingsImpl.hasInvocationListeners()).isFalse(); // when mockSettingsImpl.invocationListeners(invocationListener); // then - Assertions.assertThat(mockSettingsImpl.getInvocationListeners()) - .contains(invocationListener); + assertThat(mockSettingsImpl.getInvocationListeners()).contains(invocationListener); } @Test @SuppressWarnings("unchecked") public void canAddDuplicateInvocationListeners_ItsNotOurBusinessThere() { // given - assertFalse(mockSettingsImpl.hasInvocationListeners()); + assertThat(mockSettingsImpl.hasInvocationListeners()).isFalse(); // when mockSettingsImpl @@ -146,104 +169,69 @@ public void canAddDuplicateInvocationListeners_ItsNotOurBusinessThere() { .invocationListeners(invocationListener); // then - Assertions.assertThat(mockSettingsImpl.getInvocationListeners()) + assertThat(mockSettingsImpl.getInvocationListeners()) .containsSequence(invocationListener, invocationListener, invocationListener); } @Test public void validates_listeners() { assertThatThrownBy( - new ThrowableAssert.ThrowingCallable() { - public void call() { + () -> mockSettingsImpl.addListeners( - new Object[] {}, new LinkedList(), "myListeners"); - } - }) + new Object[] {}, new LinkedList(), "myListeners")) .hasMessageContaining("myListeners() requires at least one listener"); assertThatThrownBy( - new ThrowableAssert.ThrowingCallable() { - public void call() { + () -> mockSettingsImpl.addListeners( - null, new LinkedList(), "myListeners"); - } - }) + null, new LinkedList(), "myListeners")) .hasMessageContaining("myListeners() does not accept null vararg array"); assertThatThrownBy( - new ThrowableAssert.ThrowingCallable() { - public void call() { + () -> mockSettingsImpl.addListeners( new Object[] {null}, new LinkedList(), - "myListeners"); - } - }) + "myListeners")) .hasMessageContaining("myListeners() does not accept null listeners"); } @Test public void validates_stubbing_lookup_listeners() { assertThatThrownBy( - new ThrowableAssert.ThrowingCallable() { - public void call() { + () -> mockSettingsImpl.stubbingLookupListeners( - new StubbingLookupListener[] {}); - } - }) + new StubbingLookupListener[] {})) .hasMessageContaining("stubbingLookupListeners() requires at least one listener"); - assertThatThrownBy( - new ThrowableAssert.ThrowingCallable() { - public void call() { - mockSettingsImpl.stubbingLookupListeners(null); - } - }) + assertThatThrownBy(() -> mockSettingsImpl.stubbingLookupListeners(null)) .hasMessageContaining( "stubbingLookupListeners() does not accept null vararg array"); assertThatThrownBy( - new ThrowableAssert.ThrowingCallable() { - public void call() { + () -> mockSettingsImpl.stubbingLookupListeners( - new StubbingLookupListener[] {null}); - } - }) + new StubbingLookupListener[] {null})) .hasMessageContaining("stubbingLookupListeners() does not accept null listeners"); } @Test public void validates_invocation_listeners() { - assertThatThrownBy( - new ThrowableAssert.ThrowingCallable() { - public void call() { - mockSettingsImpl.invocationListeners(new InvocationListener[] {}); - } - }) + assertThatThrownBy(() -> mockSettingsImpl.invocationListeners(new InvocationListener[] {})) .hasMessageContaining("invocationListeners() requires at least one listener"); - assertThatThrownBy( - new ThrowableAssert.ThrowingCallable() { - public void call() { - mockSettingsImpl.invocationListeners(null); - } - }) + assertThatThrownBy(() -> mockSettingsImpl.invocationListeners(null)) .hasMessageContaining("invocationListeners() does not accept null vararg array"); assertThatThrownBy( - new ThrowableAssert.ThrowingCallable() { - public void call() { - mockSettingsImpl.invocationListeners( - new InvocationListener[] {null}); - } - }) + () -> mockSettingsImpl.invocationListeners(new InvocationListener[] {null})) .hasMessageContaining("invocationListeners() does not accept null listeners"); } @Test public void addListeners_has_empty_listeners_by_default() { - assertTrue(mockSettingsImpl.getInvocationListeners().isEmpty()); - assertTrue(mockSettingsImpl.getStubbingLookupListeners().isEmpty()); + assertThat(mockSettingsImpl.getInvocationListeners()).isEmpty(); + assertThat(mockSettingsImpl.getStubbingLookupListeners()).isEmpty(); } @Test diff --git a/src/test/java/org/mockito/internal/creation/instance/ConstructorInstantiatorTest.java b/src/test/java/org/mockito/internal/creation/instance/ConstructorInstantiatorTest.java index d576116aa2..a498073128 100644 --- a/src/test/java/org/mockito/internal/creation/instance/ConstructorInstantiatorTest.java +++ b/src/test/java/org/mockito/internal/creation/instance/ConstructorInstantiatorTest.java @@ -5,7 +5,7 @@ package org.mockito.internal.creation.instance; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.assertEquals; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import org.junit.Test; @@ -31,59 +31,61 @@ static class SomeClass3 { @Test public void creates_instances() { - assertEquals( - new ConstructorInstantiator(false, new Object[0]) - .newInstance(SomeClass.class) - .getClass(), - SomeClass.class); + assertThat( + new ConstructorInstantiator(false, new Object[0]) + .newInstance(SomeClass.class) + .getClass()) + .isEqualTo(SomeClass.class); } @Test public void creates_instances_of_inner_classes() { - assertEquals( - new ConstructorInstantiator(true, this) - .newInstance(SomeInnerClass.class) - .getClass(), - SomeInnerClass.class); - assertEquals( - new ConstructorInstantiator(true, new ChildOfThis()) - .newInstance(SomeInnerClass.class) - .getClass(), - SomeInnerClass.class); + assertThat( + new ConstructorInstantiator(true, this) + .newInstance(SomeInnerClass.class) + .getClass()) + .isEqualTo(SomeInnerClass.class); + assertThat( + new ConstructorInstantiator(true, new ChildOfThis()) + .newInstance(SomeInnerClass.class) + .getClass()) + .isEqualTo(SomeInnerClass.class); } @Test public void creates_instances_with_arguments() { - assertEquals( - new ConstructorInstantiator(false, "someString") - .newInstance(SomeClass2.class) - .getClass(), - SomeClass2.class); + assertThat( + new ConstructorInstantiator(false, "someString") + .newInstance(SomeClass2.class) + .getClass()) + .isEqualTo(SomeClass2.class); } @Test public void creates_instances_with_null_arguments() { - assertEquals( - new ConstructorInstantiator(false, new Object[] {null}) - .newInstance(SomeClass2.class) - .getClass(), - SomeClass2.class); + assertThat( + new ConstructorInstantiator(false, new Object[] {null}) + .newInstance(SomeClass2.class) + .getClass()) + .isEqualTo(SomeClass2.class); } @Test public void creates_instances_with_primitive_arguments() { - assertEquals( - new ConstructorInstantiator(false, 123).newInstance(SomeClass3.class).getClass(), - SomeClass3.class); + assertThat(new ConstructorInstantiator(false, 123).newInstance(SomeClass3.class).getClass()) + .isEqualTo(SomeClass3.class); } - @Test(expected = org.mockito.creation.instance.InstantiationException.class) + @Test public void fails_when_null_is_passed_for_a_primitive() { - assertEquals( - new ConstructorInstantiator(false, new Object[] {null}) - .newInstance(SomeClass3.class) - .getClass(), - SomeClass3.class); + assertThatThrownBy( + () -> { + new ConstructorInstantiator(false, new Object[] {null}) + .newInstance(SomeClass3.class) + .getClass(); + }) + .isInstanceOf(org.mockito.creation.instance.InstantiationException.class) + .hasMessageContaining("Unable to create instance of 'SomeClass3'."); } @Test diff --git a/src/test/java/org/mockito/internal/exceptions/ReporterTest.java b/src/test/java/org/mockito/internal/exceptions/ReporterTest.java index 3b71be348f..9e4ca2381a 100644 --- a/src/test/java/org/mockito/internal/exceptions/ReporterTest.java +++ b/src/test/java/org/mockito/internal/exceptions/ReporterTest.java @@ -4,6 +4,7 @@ */ package org.mockito.internal.exceptions; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import java.lang.reflect.Field; @@ -23,97 +24,176 @@ public class ReporterTest extends TestBase { - @Test(expected = TooFewActualInvocations.class) - public void should_let_passing_null_last_actual_stack_trace() throws Exception { - throw Reporter.tooFewActualInvocations( - new org.mockito.internal.reporting.Discrepancy(1, 2), - new InvocationBuilder().toInvocation(), - null); + @Test + public void should_let_passing_null_last_actual_stack_trace() { + assertThatThrownBy( + () -> { + throw Reporter.tooFewActualInvocations( + new org.mockito.internal.reporting.Discrepancy(1, 2), + new InvocationBuilder().toInvocation(), + null); + }) + .isInstanceOf(TooFewActualInvocations.class) + .hasMessageContainingAll( + "iMethods.simpleMethod();", "Wanted 1 time:", "But was 2 times:"); } - @Test(expected = MockitoException.class) - public void should_throw_correct_exception_for_null_invocation_listener() throws Exception { - throw Reporter.methodDoesNotAcceptParameter("invocationListeners", "null vararg array"); + @Test + public void should_throw_correct_exception_for_null_invocation_listener() { + assertThatThrownBy( + () -> { + throw Reporter.methodDoesNotAcceptParameter( + "invocationListeners", "null vararg array"); + }) + .isInstanceOf(MockitoException.class) + .hasMessage( + "invocationListeners() does not accept null vararg array See the Javadoc."); } - @Test(expected = NoInteractionsWanted.class) + @Test public void - can_use_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_no_more_interaction_wanted() - throws Exception { + can_use_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_no_more_interaction_wanted() { Invocation invocation_with_bogus_default_answer = new InvocationBuilder() .mock(mock(IMethods.class, new Returns(false))) .toInvocation(); - throw Reporter.noMoreInteractionsWanted( - invocation_with_bogus_default_answer, - Collections.emptyList()); + + assertThatThrownBy( + () -> { + throw Reporter.noMoreInteractionsWanted( + invocation_with_bogus_default_answer, + Collections.emptyList()); + }) + .isInstanceOf(NoInteractionsWanted.class) + .hasMessageContainingAll( + "No interactions wanted here:", + "But found this interaction on mock 'iMethods':"); } - @Test(expected = VerificationInOrderFailure.class) + @Test public void - can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_no_more_interaction_wanted_in_order() - throws Exception { + can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_no_more_interaction_wanted_in_order() { Invocation invocation_with_bogus_default_answer = new InvocationBuilder() .mock(mock(IMethods.class, new Returns(false))) .toInvocation(); - throw Reporter.noMoreInteractionsWantedInOrder(invocation_with_bogus_default_answer); + + assertThatThrownBy( + () -> { + throw Reporter.noMoreInteractionsWantedInOrder( + invocation_with_bogus_default_answer); + }) + .isInstanceOf(VerificationInOrderFailure.class) + .hasMessageContainingAll( + "No interactions wanted here:", + "But found this interaction on mock 'iMethods':"); } - @Test(expected = MockitoException.class) + @Test public void - can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_invalid_argument_position() - throws Exception { + can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_invalid_argument_position() { Invocation invocation_with_bogus_default_answer = new InvocationBuilder() .mock(mock(IMethods.class, new Returns(false))) .toInvocation(); - throw Reporter.invalidArgumentPositionRangeAtInvocationTime( - invocation_with_bogus_default_answer, true, 0); + + assertThatThrownBy( + () -> { + throw Reporter.invalidArgumentPositionRangeAtInvocationTime( + invocation_with_bogus_default_answer, true, 0); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "Invalid argument index for the current invocation of method :", + " -> iMethods.simpleMethod()", + "Last parameter wanted but the method has no arguments."); } - @Test(expected = MockitoException.class) + @Test public void - can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_wrong_argument_to_return() - throws Exception { + can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_wrong_argument_to_return() { Invocation invocation_with_bogus_default_answer = new InvocationBuilder() .mock(mock(IMethods.class, new Returns(false))) .toInvocation(); - throw Reporter.wrongTypeOfArgumentToReturn( - invocation_with_bogus_default_answer, "", String.class, 0); + + assertThatThrownBy( + () -> { + throw Reporter.wrongTypeOfArgumentToReturn( + invocation_with_bogus_default_answer, "", String.class, 0); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "The argument of type 'String' cannot be returned because the following", + "method should return the type ''", + " -> iMethods.simpleMethod()", + "The reason for this error can be :", + "1. The wanted argument position is incorrect.", + "2. The answer is used on the wrong interaction.", + "Position of the wanted argument is 0 and the method has no arguments."); } - @Test(expected = MockitoException.class) + @Test public void - can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_delegate_method_dont_exists() - throws Exception { + can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_delegate_method_dont_exists() { Invocation dumb_invocation = new InvocationBuilder().toInvocation(); IMethods mock_with_bogus_default_answer = mock(IMethods.class, new Returns(false)); - throw Reporter.delegatedMethodDoesNotExistOnDelegate( - dumb_invocation.getMethod(), mock_with_bogus_default_answer, String.class); + + assertThatThrownBy( + () -> { + throw Reporter.delegatedMethodDoesNotExistOnDelegate( + dumb_invocation.getMethod(), + mock_with_bogus_default_answer, + String.class); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "Methods called on mock must exist in delegated instance.", + "When calling: public abstract java.lang.String org.mockitousage.IMethods.simpleMethod() on mock: iMethods", + "no such method was found.", + "Check that the instance passed to delegatesTo() is of the correct type or contains compatible methods", + "(delegate instance had type: Class)"); } - @Test(expected = MockitoException.class) + @Test public void - can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_delegate_method_has_wrong_return_type() - throws Exception { + can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_delegate_method_has_wrong_return_type() { Invocation dumb_invocation = new InvocationBuilder().toInvocation(); IMethods mock_with_bogus_default_answer = mock(IMethods.class, new Returns(false)); - throw Reporter.delegatedMethodHasWrongReturnType( - dumb_invocation.getMethod(), - dumb_invocation.getMethod(), - mock_with_bogus_default_answer, - String.class); + + assertThatThrownBy( + () -> { + throw Reporter.delegatedMethodHasWrongReturnType( + dumb_invocation.getMethod(), + dumb_invocation.getMethod(), + mock_with_bogus_default_answer, + String.class); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "Methods called on delegated instance must have compatible return types with the mock.", + "When calling: public abstract java.lang.String org.mockitousage.IMethods.simpleMethod() on mock: iMethods", + "return type should be: String, but was: String", + "Check that the instance passed to delegatesTo() is of the correct type or contains compatible methods", + "(delegate instance had type: Class)"); } - @Test(expected = MockitoException.class) + @Test public void - can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_injection_failure() - throws Exception { + can_use_print_mock_name_even_when_mock_bogus_default_answer_and_when_reporting_injection_failure() { IMethods mock_with_bogus_default_answer = mock(IMethods.class, new Returns(false)); - throw Reporter.cannotInjectDependency( - someField(), mock_with_bogus_default_answer, new Exception()); + + assertThatThrownBy( + () -> { + throw Reporter.cannotInjectDependency( + someField(), mock_with_bogus_default_answer, new Exception()); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "Mockito couldn't inject mock dependency 'iMethods' on field", + "'static final org.mockito.internal.MockitoCore org.mockito.Mockito.MOCKITO_CORE'", + "whose type 'org.mockito.Mockito' was annotated by @InjectMocks in your test.", + "Also I failed because: null"); } private Field someField() { diff --git a/src/test/java/org/mockito/internal/framework/DefaultMockitoFrameworkTest.java b/src/test/java/org/mockito/internal/framework/DefaultMockitoFrameworkTest.java index 344621eead..3b2884e52e 100644 --- a/src/test/java/org/mockito/internal/framework/DefaultMockitoFrameworkTest.java +++ b/src/test/java/org/mockito/internal/framework/DefaultMockitoFrameworkTest.java @@ -4,6 +4,7 @@ */ package org.mockito.internal.framework; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assume.assumeTrue; @@ -41,14 +42,24 @@ public void clearListeners() { new StateMaster().clearMockitoListeners(); } - @Test(expected = IllegalArgumentException.class) + @Test public void prevents_adding_null_listener() { - framework.addListener(null); + assertThatThrownBy( + () -> { + framework.addListener(null); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("listener should not be null"); } - @Test(expected = IllegalArgumentException.class) + @Test public void prevents_removing_null_listener() { - framework.removeListener(null); + assertThatThrownBy( + () -> { + framework.removeListener(null); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessage("listener should not be null"); } @Test diff --git a/src/test/java/org/mockito/internal/handler/InvocationNotifierHandlerTest.java b/src/test/java/org/mockito/internal/handler/InvocationNotifierHandlerTest.java index 273674f614..54e8394c09 100644 --- a/src/test/java/org/mockito/internal/handler/InvocationNotifierHandlerTest.java +++ b/src/test/java/org/mockito/internal/handler/InvocationNotifierHandlerTest.java @@ -5,6 +5,7 @@ package org.mockito.internal.handler; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; @@ -49,7 +50,7 @@ public class InvocationNotifierHandlerTest { @Before public void setUp() throws Exception { notifier = - new InvocationNotifierHandler>>( + new InvocationNotifierHandler<>( mockHandler, (MockCreationSettings>>) new MockSettingsImpl>>() @@ -90,7 +91,7 @@ public void should_notify_all_listeners_when_called_delegate_handler_returns_ex( new NotifiedMethodInvocationReport(invocation, (Object) computedException)); } - @Test(expected = ParseException.class) + @Test public void should_notify_all_listeners_when_called_delegate_handler_throws_exception_and_rethrow_it() throws Throwable { @@ -99,18 +100,18 @@ public void should_notify_all_listeners_when_called_delegate_handler_returns_ex( given(mockHandler.handle(invocation)).willThrow(parseException); // when - try { - notifier.handle(invocation); - fail(); - } finally { - // then - verify(listener1) - .reportInvocation( - new NotifiedMethodInvocationReport(invocation, parseException)); - verify(listener2) - .reportInvocation( - new NotifiedMethodInvocationReport(invocation, parseException)); - } + assertThatThrownBy( + () -> { + notifier.handle(invocation); + }) + .isInstanceOf(ParseException.class) + .hasMessage(""); + + // then + verify(listener1) + .reportInvocation(new NotifiedMethodInvocationReport(invocation, parseException)); + verify(listener2) + .reportInvocation(new NotifiedMethodInvocationReport(invocation, parseException)); } @Test @@ -132,8 +133,7 @@ public void should_report_listener_exception() throws Throwable { } @Test - public void should_delegate_all_MockHandlerInterface_to_the_parameterized_MockHandler() - throws Exception { + public void should_delegate_all_MockHandlerInterface_to_the_parameterized_MockHandler() { notifier.getInvocationContainer(); notifier.getMockSettings(); diff --git a/src/test/java/org/mockito/internal/handler/MockHandlerImplTest.java b/src/test/java/org/mockito/internal/handler/MockHandlerImplTest.java index b109b7eeca..a0169c25f8 100644 --- a/src/test/java/org/mockito/internal/handler/MockHandlerImplTest.java +++ b/src/test/java/org/mockito/internal/handler/MockHandlerImplTest.java @@ -4,16 +4,15 @@ */ package org.mockito.internal.handler; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertNull; import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.given; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.internal.progress.ThreadSafeMockingProgress.mockingProgress; -import java.util.Arrays; - import org.junit.Test; import org.mockito.exceptions.base.MockitoException; import org.mockito.exceptions.misusing.InvalidUseOfMatchersException; @@ -23,8 +22,6 @@ import org.mockito.internal.invocation.InvocationMatcher; import org.mockito.internal.invocation.MatchersBinder; import org.mockito.internal.progress.ArgumentMatcherStorage; -import org.mockito.internal.stubbing.InvocationContainerImpl; -import org.mockito.internal.stubbing.StubbedInvocationMatcher; import org.mockito.internal.stubbing.answers.Returns; import org.mockito.internal.verification.VerificationModeFactory; import org.mockito.invocation.Invocation; @@ -32,13 +29,9 @@ import org.mockito.listeners.MethodInvocationReport; import org.mockitoutil.TestBase; -@SuppressWarnings({"unchecked", "serial"}) +@SuppressWarnings({"unchecked"}) public class MockHandlerImplTest extends TestBase { - private StubbedInvocationMatcher stubbedInvocationMatcher = - mock(StubbedInvocationMatcher.class); - private Invocation invocation = mock(Invocation.class); - @Test public void should_remove_verification_mode_even_when_invalid_matchers() throws Throwable { // given @@ -66,59 +59,46 @@ public InvocationMatcher bindMatchers( assertNull(mockingProgress().pullVerificationMode()); } - @Test(expected = MockitoException.class) - public void should_throw_mockito_exception_when_invocation_handler_throws_anything() - throws Throwable { + @Test + public void should_throw_mockito_exception_when_invocation_handler_throws_anything() { // given InvocationListener throwingListener = mock(InvocationListener.class); - doThrow(new Throwable()) - .when(throwingListener) - .reportInvocation(any(MethodInvocationReport.class)); - MockHandlerImpl handler = create_correctly_stubbed_handler(throwingListener); - - // when - handler.handle(invocation); + // when / then + assertThatThrownBy( + () -> { + doThrow(new Throwable()) + .when(throwingListener) + .reportInvocation(any(MethodInvocationReport.class)); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "Checked exception is invalid for this method!", + "Invalid: java.lang.Throwable"); } - @Test(expected = WrongTypeOfReturnValue.class) + @Test public void should_report_bogus_default_answer() throws Throwable { + // given MockSettingsImpl mockSettings = mock(MockSettingsImpl.class); MockHandlerImpl handler = new MockHandlerImpl(mockSettings); given(mockSettings.getDefaultAnswer()).willReturn(new Returns(AWrongType.WRONG_TYPE)); - - @SuppressWarnings("unused") // otherwise cast is not done - String there_should_not_be_a_CCE_here = - (String) - handler.handle( - new InvocationBuilder() - .method(Object.class.getDeclaredMethod("toString")) - .toInvocation()); - } - - private MockHandlerImpl create_correctly_stubbed_handler( - InvocationListener throwingListener) { - MockHandlerImpl handler = create_handler_with_listeners(throwingListener); - stub_ordinary_invocation_with_given_return_value(handler); - return handler; - } - - private void stub_ordinary_invocation_with_given_return_value(MockHandlerImpl handler) { - stub_ordinary_invocation_with_invocation_matcher(handler, stubbedInvocationMatcher); - } - - private void stub_ordinary_invocation_with_invocation_matcher( - MockHandlerImpl handler, StubbedInvocationMatcher value) { - handler.invocationContainer = mock(InvocationContainerImpl.class); - given(handler.invocationContainer.findAnswerFor(any(Invocation.class))).willReturn(value); - } - - private MockHandlerImpl create_handler_with_listeners(InvocationListener... listener) { - @SuppressWarnings("rawtypes") - MockHandlerImpl handler = new MockHandlerImpl(mock(MockSettingsImpl.class)); - handler.matchersBinder = mock(MatchersBinder.class); - given(handler.getMockSettings().getInvocationListeners()) - .willReturn(Arrays.asList(listener)); - return handler; + Invocation invocation = + new InvocationBuilder() + .method(Object.class.getDeclaredMethod("toString")) + .toInvocation(); + // when / then + assertThatThrownBy( + () -> { + @SuppressWarnings("unused") // otherwise cast is not done + String there_should_not_be_a_CCE_here = + (String) handler.handle(invocation); + }) + .isInstanceOf(WrongTypeOfReturnValue.class) + .hasMessageContainingAll( + "Default answer returned a result with the wrong type:", + "AWrongType cannot be returned by toString()", + "toString() should return String", + "The default answer of iMethods that was configured on the mock is probably incorrectly implemented."); } private static class AWrongType { diff --git a/src/test/java/org/mockito/internal/progress/TimesTest.java b/src/test/java/org/mockito/internal/progress/TimesTest.java index a981e48e19..1605d60e6f 100644 --- a/src/test/java/org/mockito/internal/progress/TimesTest.java +++ b/src/test/java/org/mockito/internal/progress/TimesTest.java @@ -4,21 +4,21 @@ */ package org.mockito.internal.progress; -import org.junit.Rule; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.exceptions.base.MockitoException; import org.mockito.internal.verification.VerificationModeFactory; public class TimesTest { - @Rule public ExpectedException exception = ExpectedException.none(); @Test - public void shouldNotAllowNegativeNumberOfInvocations() throws Exception { - - exception.expect(MockitoException.class); - exception.expectMessage("Negative value is not allowed here"); - - VerificationModeFactory.times(-50); + public void shouldNotAllowNegativeNumberOfInvocations() { + assertThatThrownBy( + () -> { + VerificationModeFactory.times(-50); + }) + .isInstanceOf(MockitoException.class) + .hasMessage("Negative value is not allowed here"); } } diff --git a/src/test/java/org/mockito/internal/stubbing/answers/AnswersWithDelayTest.java b/src/test/java/org/mockito/internal/stubbing/answers/AnswersWithDelayTest.java index 9f90d173df..e507f2fd44 100644 --- a/src/test/java/org/mockito/internal/stubbing/answers/AnswersWithDelayTest.java +++ b/src/test/java/org/mockito/internal/stubbing/answers/AnswersWithDelayTest.java @@ -5,6 +5,7 @@ package org.mockito.internal.stubbing.answers; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.within; import java.util.Date; @@ -26,14 +27,28 @@ public void should_return_value() throws Throwable { .isEqualTo("value"); } - @Test(expected = MockitoException.class) - public void should_fail_when_contained_answer_should_fail() throws Throwable { - new AnswersWithDelay(1, new Returns("one")) - .validateFor(new InvocationBuilder().method("voidMethod").toInvocation()); + @Test + public void should_fail_when_contained_answer_should_fail() { + assertThatThrownBy( + () -> { + new AnswersWithDelay(1, new Returns("one")) + .validateFor( + new InvocationBuilder() + .method("voidMethod") + .toInvocation()); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "'voidMethod' is a *void method* and it *cannot* be stubbed with a *return value*!", + "Voids are usually stubbed with Throwables:", + " doThrow(exception).when(mock).someVoidMethod();", + "If you need to set the void method to do nothing you can use:", + " doNothing().when(mock).someVoidMethod();", + "For more information, check out the javadocs for Mockito.doNothing()."); } @Test - public void should_succeed_when_contained_answer_should_succeed() throws Throwable { + public void should_succeed_when_contained_answer_should_succeed() { new AnswersWithDelay(1, new Returns("one")) .validateFor(new InvocationBuilder().simpleMethod().toInvocation()); } diff --git a/src/test/java/org/mockito/internal/stubbing/answers/DoesNothingTest.java b/src/test/java/org/mockito/internal/stubbing/answers/DoesNothingTest.java index adb7974c61..ecdd6cb761 100644 --- a/src/test/java/org/mockito/internal/stubbing/answers/DoesNothingTest.java +++ b/src/test/java/org/mockito/internal/stubbing/answers/DoesNothingTest.java @@ -5,6 +5,7 @@ package org.mockito.internal.stubbing.answers; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.doNothing; import static org.mockito.Mockito.mock; import static org.mockito.internal.stubbing.answers.DoesNothing.doesNothing; @@ -38,15 +39,20 @@ public void init() { } @Test - public void answer_returnsNull() throws Throwable { + public void answer_returnsNull() { assertThat(doesNothing().answer(invocation_Void)).isNull(); assertThat(doesNothing().answer(invocation_void)).isNull(); assertThat(doesNothing().answer(invocation_String)).isNull(); } - @Test(expected = MockitoException.class) + @Test public void validateFor_nonVoidReturnType_shouldFail() { - doesNothing().validateFor(invocation_String); + assertThatThrownBy( + () -> { + doesNothing().validateFor(invocation_String); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("Only void methods can doNothing()!"); } @Test @@ -55,7 +61,7 @@ public void validateFor_voidReturnType_shouldPass() { } @Test - public void validateFor_voidObjectReturnType() throws Throwable { + public void validateFor_voidObjectReturnType() { doesNothing().validateFor(invocation_Void); } diff --git a/src/test/java/org/mockito/internal/stubbing/answers/ReturnsTest.java b/src/test/java/org/mockito/internal/stubbing/answers/ReturnsTest.java index 7c5980602c..b18bf5a0f4 100644 --- a/src/test/java/org/mockito/internal/stubbing/answers/ReturnsTest.java +++ b/src/test/java/org/mockito/internal/stubbing/answers/ReturnsTest.java @@ -5,8 +5,8 @@ package org.mockito.internal.stubbing.answers; import static java.lang.Boolean.TRUE; - import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.junit.Test; import org.mockito.exceptions.base.MockitoException; @@ -25,13 +25,23 @@ public void should_return_value() throws Throwable { .isEqualTo("value"); } - @Test(expected = MockitoException.class) - public void should_fail_when_return_Value_is_set_for_void_method() throws Throwable { - new Returns("one").validateFor(new InvocationBuilder().method("voidMethod").toInvocation()); + @Test + public void should_fail_when_return_Value_is_set_for_void_method() { + assertThatThrownBy( + () -> { + new Returns("one") + .validateFor( + new InvocationBuilder() + .method("voidMethod") + .toInvocation()); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining( + "'voidMethod' is a *void method* and it *cannot* be stubbed with a *return value*!"); } @Test - public void should_allow_correct_type_of_return_value() throws Throwable { + public void should_allow_correct_type_of_return_value() { new Returns("one").validateFor(new InvocationBuilder().simpleMethod().toInvocation()); new Returns(false) .validateFor( @@ -61,24 +71,51 @@ public void should_allow_correct_type_of_return_value() throws Throwable { .toInvocation()); } - @Test(expected = MockitoException.class) - public void should_fail_on_return_type_mismatch() throws Throwable { - new Returns("String") - .validateFor( - new InvocationBuilder().method("booleanReturningMethod").toInvocation()); + @Test + public void should_fail_on_return_type_mismatch() { + assertThatThrownBy( + () -> { + new Returns("String") + .validateFor( + new InvocationBuilder() + .method("booleanReturningMethod") + .toInvocation()); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "String cannot be returned by booleanReturningMethod()", + "booleanReturningMethod() should return boolean"); } - @Test(expected = MockitoException.class) - public void should_fail_on_wrong_primitive() throws Throwable { - new Returns(1) - .validateFor( - new InvocationBuilder().method("doubleReturningMethod").toInvocation()); + @Test + public void should_fail_on_wrong_primitive() { + assertThatThrownBy( + () -> { + new Returns(1) + .validateFor( + new InvocationBuilder() + .method("doubleReturningMethod") + .toInvocation()); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "Integer cannot be returned by doubleReturningMethod()", + "doubleReturningMethod() should return double"); } - @Test(expected = MockitoException.class) - public void should_fail_on_null_with_primitive() throws Throwable { - new Returns(null) - .validateFor( - new InvocationBuilder().method("booleanReturningMethod").toInvocation()); + @Test + public void should_fail_on_null_with_primitive() { + assertThatThrownBy( + () -> { + new Returns(null) + .validateFor( + new InvocationBuilder() + .method("booleanReturningMethod") + .toInvocation()); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "null cannot be returned by booleanReturningMethod()", + "booleanReturningMethod() should return boolean"); } } diff --git a/src/test/java/org/mockito/internal/stubbing/answers/ThrowsExceptionTest.java b/src/test/java/org/mockito/internal/stubbing/answers/ThrowsExceptionTest.java index 9b8e799e29..281018101b 100644 --- a/src/test/java/org/mockito/internal/stubbing/answers/ThrowsExceptionTest.java +++ b/src/test/java/org/mockito/internal/stubbing/answers/ThrowsExceptionTest.java @@ -6,6 +6,7 @@ import static junit.framework.TestCase.fail; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertSame; import static org.mockito.Mockito.mock; @@ -20,7 +21,7 @@ public class ThrowsExceptionTest { @Test - public void should_raise_wanted_throwable() throws Throwable { + public void should_raise_wanted_throwable() { try { new ThrowsException(new IllegalStateException("my dear throwable")) .answer(createMethodInvocation()); @@ -33,7 +34,7 @@ public void should_raise_wanted_throwable() throws Throwable { } @Test - public void should_throw_mock_exception_without_stacktrace() throws Exception { + public void should_throw_mock_exception_without_stacktrace() { try { new ThrowsException(mock(Exception.class)).answer(createMethodInvocation()); Assertions.fail("should have raised wanted exception"); @@ -43,7 +44,7 @@ public void should_throw_mock_exception_without_stacktrace() throws Exception { } @Test - public void should_fill_in_exception_stacktrace() throws Exception { + public void should_fill_in_exception_stacktrace() { // given Exception throwableToRaise = new Exception(); throwableToRaise.fillInStackTrace(); @@ -66,7 +67,7 @@ public void should_fill_in_exception_stacktrace() throws Exception { } @Test - public void should_invalidate_null_throwable() throws Throwable { + public void should_invalidate_null_throwable() { try { Invocation invocation = createMethodInvocation(); new ThrowsException(null).validateFor(invocation); @@ -86,17 +87,25 @@ public void should_throw_illegal_state_exception_if_null_answer() throws Throwab } @Test - public void should_pass_proper_checked_exception() throws Throwable { + public void should_pass_proper_checked_exception() { new ThrowsException(new CharacterCodingException()).validateFor(createMethodInvocation()); } - @Test(expected = MockitoException.class) - public void should_fail_invalid_checked_exception() throws Throwable { - new ThrowsException(new IOException()).validateFor(createMethodInvocation()); + @Test + public void should_fail_invalid_checked_exception() { + assertThatThrownBy( + () -> { + new ThrowsException(new IOException()) + .validateFor(createMethodInvocation()); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "Checked exception is invalid for this method!", + "Invalid: java.io.IOException"); } @Test - public void should_pass_RuntimeExceptions() throws Throwable { + public void should_pass_RuntimeExceptions() { new ThrowsException(new Error()).validateFor(createMethodInvocation()); new ThrowsException(new RuntimeException()).validateFor(createMethodInvocation()); } diff --git a/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsGenericDeepStubsTest.java b/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsGenericDeepStubsTest.java index fb239c09be..21f2e3e7c5 100644 --- a/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsGenericDeepStubsTest.java +++ b/src/test/java/org/mockito/internal/stubbing/defaultanswers/ReturnsGenericDeepStubsTest.java @@ -5,6 +5,7 @@ package org.mockito.internal.stubbing.defaultanswers; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -124,14 +125,16 @@ public void will_return_default_value_on_non_mockable_nested_generic() { assertThat(anotherListOfInteger.get(25)).isEqualTo(0); } - @Test(expected = ClassCastException.class) + @Test public void as_expected_fail_with_a_CCE_on_call_site_when_erasure_takes_place_for_example___StringBuilder_is_subject_to_erasure() { GenericsNest mock = mock(GenericsNest.class, RETURNS_DEEP_STUBS); - // following assignment needed to create a ClassCastException on the call site (i.e. : here) - StringBuilder stringBuilder_assignment_that_should_throw_a_CCE = - mock.twoTypeParams(new StringBuilder()).append(2).append(3); + assertThatThrownBy( + () -> { + mock.twoTypeParams(new StringBuilder()).append(2).append(3); + }) + .isInstanceOf(ClassCastException.class); } class WithGenerics { diff --git a/src/test/java/org/mockito/internal/util/ChecksTest.java b/src/test/java/org/mockito/internal/util/ChecksTest.java index 21d067d624..6b640dbe01 100644 --- a/src/test/java/org/mockito/internal/util/ChecksTest.java +++ b/src/test/java/org/mockito/internal/util/ChecksTest.java @@ -4,36 +4,40 @@ */ package org.mockito.internal.util; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; public class ChecksTest { - @Rule public ExpectedException expectedException = ExpectedException.none(); @Test - public void checkNotNull_not_null() throws Exception { + public void checkNotNull_not_null() { assertEquals("abc", Checks.checkNotNull("abc", "someValue")); } @Test - public void checkNotNull_not_null_additional_message() throws Exception { + public void checkNotNull_not_null_additional_message() { assertEquals("abc", Checks.checkNotNull("abc", "someValue", "Oh no!")); } @Test - public void checkNotNull_null() throws Exception { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("someValue should not be null"); - Checks.checkNotNull(null, "someValue"); + public void checkNotNull_null() { + assertThatThrownBy( + () -> { + Checks.checkNotNull(null, "someValue"); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("someValue should not be null"); } @Test - public void checkNotNull_null_additonal_message() throws Exception { - expectedException.expect(IllegalArgumentException.class); - expectedException.expectMessage("someValue should not be null. Oh no!"); - Checks.checkNotNull(null, "someValue", "Oh no!"); + public void checkNotNull_null_additonal_message() { + assertThatThrownBy( + () -> { + Checks.checkNotNull(null, "someValue", "Oh no!"); + }) + .isInstanceOf(IllegalArgumentException.class) + .hasMessageContaining("someValue should not be null. Oh no!"); } } diff --git a/src/test/java/org/mockito/internal/util/DefaultMockingDetailsTest.java b/src/test/java/org/mockito/internal/util/DefaultMockingDetailsTest.java index b199054e3f..1a126d6dd7 100644 --- a/src/test/java/org/mockito/internal/util/DefaultMockingDetailsTest.java +++ b/src/test/java/org/mockito/internal/util/DefaultMockingDetailsTest.java @@ -5,6 +5,7 @@ package org.mockito.internal.util; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; @@ -115,9 +116,15 @@ public void provides_mock_creation_settings() { assertEquals(0, mockingDetails(mock).getMockCreationSettings().getExtraInterfaces().size()); } - @Test(expected = NotAMockException.class) + @Test public void fails_when_getting_creation_settings_for_incorrect_input() { - mockingDetails(null).getMockCreationSettings(); + assertThatThrownBy( + () -> { + mockingDetails(null).getMockCreationSettings(); + }) + .isInstanceOf(NotAMockException.class) + .hasMessage( + "Argument passed to Mockito.mockingDetails() should be a mock, but is null!"); } @Test diff --git a/src/test/java/org/mockito/internal/util/MockCreationValidatorTest.java b/src/test/java/org/mockito/internal/util/MockCreationValidatorTest.java index ccb134746b..7efffcf6a2 100644 --- a/src/test/java/org/mockito/internal/util/MockCreationValidatorTest.java +++ b/src/test/java/org/mockito/internal/util/MockCreationValidatorTest.java @@ -5,8 +5,8 @@ package org.mockito.internal.util; import static java.util.Arrays.asList; - import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import java.util.ArrayList; @@ -23,8 +23,7 @@ public class MockCreationValidatorTest { MockCreationValidator validator = new MockCreationValidator(); @Test - public void should_not_allow_extra_interface_that_is_the_same_as_the_mocked_type() - throws Exception { + public void should_not_allow_extra_interface_that_is_the_same_as_the_mocked_type() { try { // when validator.validateExtraInterfaces(IMethods.class, (Collection) asList(IMethods.class)); @@ -35,22 +34,28 @@ public void should_not_allow_extra_interface_that_is_the_same_as_the_mocked_type } } - @Test(expected = MockitoException.class) - public void should_not_allow_inconsistent_types() throws Exception { - // when - validator.validateMockedType(List.class, new ArrayList()); - // then + @Test + public void should_not_allow_inconsistent_types() { + // when / then + assertThatThrownBy( + () -> { + validator.validateMockedType(List.class, new ArrayList()); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "Mocked type must be the same as the type of your spied instance.", + "Mocked type must be: ArrayList, but is: List"); } @Test - public void should_allow_only_consistent_types() throws Exception { + public void should_allow_only_consistent_types() { // when validator.validateMockedType(ArrayList.class, new ArrayList()); // then no exception is thrown } @Test - public void should_validation_be_safe_when_nulls_passed() throws Exception { + public void should_validation_be_safe_when_nulls_passed() { // when validator.validateMockedType(null, new ArrayList()); // or @@ -59,7 +64,7 @@ public void should_validation_be_safe_when_nulls_passed() throws Exception { } @Test - public void should_fail_when_type_not_mockable() throws Exception { + public void should_fail_when_type_not_mockable() { try { validator.validateType(long.class); } catch (MockitoException ex) { diff --git a/src/test/java/org/mockito/internal/util/MockUtilTest.java b/src/test/java/org/mockito/internal/util/MockUtilTest.java index 2e649eeaba..50cadb4c0c 100644 --- a/src/test/java/org/mockito/internal/util/MockUtilTest.java +++ b/src/test/java/org/mockito/internal/util/MockUtilTest.java @@ -4,7 +4,10 @@ */ package org.mockito.internal.util; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; import static org.mockito.Mockito.withSettings; import java.util.ArrayList; @@ -13,7 +16,6 @@ import org.assertj.core.api.Assertions; import org.junit.Test; import org.mockito.Mockito; -import org.mockito.exceptions.base.MockitoException; import org.mockito.exceptions.misusing.NotAMockException; import org.mockito.internal.configuration.plugins.Plugins; import org.mockitoutil.TestBase; @@ -27,14 +29,24 @@ public void should_get_handler() { assertNotNull(MockUtil.getMockHandler(mock)); } - @Test(expected = NotAMockException.class) + @Test public void should_scream_when_not_a_mock_passed() { - MockUtil.getMockHandler(""); + assertThatThrownBy( + () -> { + MockUtil.getMockHandler(""); + }) + .isInstanceOf(NotAMockException.class) + .hasMessage("Argument should be a mock, but is: class java.lang.String"); } - @Test(expected = MockitoException.class) + @Test public void should_scream_when_null_passed() { - MockUtil.getMockHandler(null); + assertThatThrownBy( + () -> { + MockUtil.getMockHandler(null); + }) + .isInstanceOf(NotAMockException.class) + .hasMessage("Argument should be a mock, but is null!"); } @Test diff --git a/src/test/java/org/mockito/internal/util/TimerTest.java b/src/test/java/org/mockito/internal/util/TimerTest.java index f12efd83c5..b0da7cdae0 100644 --- a/src/test/java/org/mockito/internal/util/TimerTest.java +++ b/src/test/java/org/mockito/internal/util/TimerTest.java @@ -4,15 +4,14 @@ */ package org.mockito.internal.util; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + import org.assertj.core.api.Assertions; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.exceptions.misusing.FriendlyReminderException; import org.mockitoutil.TestBase; public class TimerTest extends TestBase { - @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void should_return_true_if_task_is_in_acceptable_time_bounds() { @@ -42,9 +41,12 @@ public void should_return_false_when_time_run_out() throws Exception { @Test public void should_throw_friendly_reminder_exception_when_duration_is_negative() { - expectedException.expect(FriendlyReminderException.class); - expectedException.expectMessage("Don't panic! I'm just a friendly reminder!"); - new Timer(-1); + assertThatThrownBy( + () -> { + new Timer(-1); + }) + .isInstanceOf(FriendlyReminderException.class) + .hasMessageContaining("Don't panic! I'm just a friendly reminder!"); } private void oneMillisecondPasses() throws InterruptedException { diff --git a/src/test/java/org/mockito/internal/util/collections/HashCodeAndEqualsSafeSetTest.java b/src/test/java/org/mockito/internal/util/collections/HashCodeAndEqualsSafeSetTest.java index 9e03b1de34..0012a59cb4 100644 --- a/src/test/java/org/mockito/internal/util/collections/HashCodeAndEqualsSafeSetTest.java +++ b/src/test/java/org/mockito/internal/util/collections/HashCodeAndEqualsSafeSetTest.java @@ -5,6 +5,7 @@ package org.mockito.internal.util.collections; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import java.util.HashSet; @@ -112,13 +113,17 @@ public void toArray_just_work() throws Exception { assertThat(mocks.toArray(new UnmockableHashCodeAndEquals[0])[0]).isSameAs(mock1); } - @Test(expected = CloneNotSupportedException.class) - public void cloneIsNotSupported() throws CloneNotSupportedException { - Object ignored = HashCodeAndEqualsSafeSet.of().clone(); + @Test + public void cloneIsNotSupported() { + assertThatThrownBy( + () -> { + HashCodeAndEqualsSafeSet.of().clone(); + }) + .isInstanceOf(CloneNotSupportedException.class); } @Test - public void isEmptyAfterClear() throws Exception { + public void isEmptyAfterClear() { HashCodeAndEqualsSafeSet set = HashCodeAndEqualsSafeSet.of(mock1); set.clear(); diff --git a/src/test/java/org/mockito/internal/util/reflection/FieldInitializerTest.java b/src/test/java/org/mockito/internal/util/reflection/FieldInitializerTest.java index 47a8769c4c..3c9e489814 100644 --- a/src/test/java/org/mockito/internal/util/reflection/FieldInitializerTest.java +++ b/src/test/java/org/mockito/internal/util/reflection/FieldInitializerTest.java @@ -4,9 +4,15 @@ */ package org.mockito.internal.util.reflection; -import static org.junit.Assert.*; -import static org.mockito.BDDMockito.given; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +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.mockito.ArgumentMatchers.any; +import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.mock; import java.lang.reflect.Field; @@ -75,11 +81,18 @@ public void should_instantiate_field_with_private_default_constructor() throws E assertFalse(report.fieldWasInitializedUsingContructorArgs()); } - @Test(expected = MockitoException.class) + @Test public void should_fail_to_instantiate_field_if_no_default_constructor() throws Exception { FieldInitializer fieldInitializer = new FieldInitializer(this, field("noDefaultConstructor")); - fieldInitializer.initialize(); + + assertThatThrownBy( + () -> { + fieldInitializer.initialize(); + }) + .isInstanceOf(MockitoException.class) + .hasMessage( + "the type 'StaticClassWithoutDefaultConstructor' has no default constructor"); } @Test @@ -97,9 +110,14 @@ public void should_fail_to_instantiate_field_if_default_constructor_throws_excep } } - @Test(expected = MockitoException.class) - public void should_fail_for_abstract_field() throws Exception { - new FieldInitializer(this, field("abstractType")); + @Test + public void should_fail_for_abstract_field() { + assertThatThrownBy( + () -> { + new FieldInitializer(this, field("abstractType")); + }) + .isInstanceOf(MockitoException.class) + .hasMessage("the type 'AbstractStaticClass' is an abstract class."); } @Test @@ -107,9 +125,14 @@ public void should_not_fail_if_abstract_field_is_instantiated() throws Exception new FieldInitializer(this, field("instantiatedAbstractType")); } - @Test(expected = MockitoException.class) - public void should_fail_for_interface_field() throws Exception { - new FieldInitializer(this, field("interfaceType")); + @Test + public void should_fail_for_interface_field() { + assertThatThrownBy( + () -> { + new FieldInitializer(this, field("interfaceType")); + }) + .isInstanceOf(MockitoException.class) + .hasMessage("the type 'Interface' is an interface."); } @Test @@ -117,9 +140,9 @@ public void should_not_fail_if_interface_field_is_instantiated() throws Exceptio new FieldInitializer(this, field("instantiatedInterfaceType")); } - @Test(expected = MockitoException.class) - public void should_fail_for_local_type_field() throws Exception { - // when + @Test + public void should_fail_for_local_type_field() { + // given class LocalType {} class TheTestWithLocalType { @@ -128,9 +151,15 @@ class TheTestWithLocalType { TheTestWithLocalType testWithLocalType = new TheTestWithLocalType(); - // when - new FieldInitializer( - testWithLocalType, testWithLocalType.getClass().getDeclaredField("field")); + // when / then + assertThatThrownBy( + () -> { + new FieldInitializer( + testWithLocalType, + testWithLocalType.getClass().getDeclaredField("field")); + }) + .isInstanceOf(MockitoException.class) + .hasMessage("the type 'LocalType' is a local class."); } @Test @@ -149,9 +178,14 @@ class TheTestWithLocalType { testWithLocalType, testWithLocalType.getClass().getDeclaredField("field")); } - @Test(expected = MockitoException.class) - public void should_fail_for_inner_class_field() throws Exception { - new FieldInitializer(this, field("innerClassType")); + @Test + public void should_fail_for_inner_class_field() { + assertThatThrownBy( + () -> { + new FieldInitializer(this, field("innerClassType")); + }) + .isInstanceOf(MockitoException.class) + .hasMessage("the type 'InnerClassType' is an inner non static class."); } @Test @@ -192,7 +226,7 @@ private StaticClassWithoutDefaultConstructor(String param) {} } static class StaticClassThrowingExceptionDefaultConstructor { - StaticClassThrowingExceptionDefaultConstructor() throws Exception { + StaticClassThrowingExceptionDefaultConstructor() { throw new NullPointerException("business logic failed"); } } diff --git a/src/test/java/org/mockito/internal/verification/VerificationOverTimeImplTest.java b/src/test/java/org/mockito/internal/verification/VerificationOverTimeImplTest.java index 4200462f45..cc214b763b 100644 --- a/src/test/java/org/mockito/internal/verification/VerificationOverTimeImplTest.java +++ b/src/test/java/org/mockito/internal/verification/VerificationOverTimeImplTest.java @@ -4,15 +4,13 @@ */ package org.mockito.internal.verification; -import static org.hamcrest.CoreMatchers.is; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; import static org.mockito.MockitoAnnotations.openMocks; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.exceptions.base.MockitoAssertionError; import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent; @@ -22,8 +20,6 @@ public class VerificationOverTimeImplTest { @Mock private VerificationMode delegate; private VerificationOverTimeImpl impl; - @Rule public ExpectedException exception = ExpectedException.none(); - @Before public void setUp() { openMocks(this); @@ -39,28 +35,36 @@ public void should_return_on_success() { @Test public void should_throw_mockito_assertion_error() { MockitoAssertionError toBeThrown = new MockitoAssertionError("message"); - exception.expect(is(toBeThrown)); doThrow(toBeThrown).when(delegate).verify(null); - impl.verify(null); + assertThatThrownBy( + () -> { + impl.verify(null); + }) + .isEqualTo(toBeThrown); } @Test public void should_deal_with_junit_assertion_error() { ArgumentsAreDifferent toBeThrown = new ArgumentsAreDifferent("message", "wanted", "actual"); - exception.expect(is(toBeThrown)); - exception.expectMessage("message"); doThrow(toBeThrown).when(delegate).verify(null); - impl.verify(null); + assertThatThrownBy( + () -> { + impl.verify(null); + }) + .isEqualTo(toBeThrown); } @Test public void should_not_wrap_other_exceptions() { RuntimeException toBeThrown = new RuntimeException(); - exception.expect(is(toBeThrown)); doThrow(toBeThrown).when(delegate).verify(null); - impl.verify(null); + assertThatThrownBy( + () -> { + impl.verify(null); + }) + .isEqualTo(toBeThrown); } } diff --git a/src/test/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsCheckerTest.java b/src/test/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsCheckerTest.java index 3f47758eb6..3087003712 100644 --- a/src/test/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsCheckerTest.java +++ b/src/test/java/org/mockito/internal/verification/checkers/AtLeastXNumberOfInvocationsCheckerTest.java @@ -5,13 +5,11 @@ package org.mockito.internal.verification.checkers; import static java.util.Arrays.asList; - import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.internal.verification.checkers.AtLeastXNumberOfInvocationsChecker.checkAtLeastNumberOfInvocations; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.exceptions.verification.TooFewActualInvocations; import org.mockito.exceptions.verification.VerificationInOrderFailure; import org.mockito.internal.invocation.InvocationBuilder; @@ -22,8 +20,6 @@ public class AtLeastXNumberOfInvocationsCheckerTest { - @Rule public ExpectedException exception = ExpectedException.none(); - @Test public void shouldMarkActualInvocationsAsVerifiedInOrder() { InOrderContext context = new InOrderContextImpl(); @@ -46,14 +42,17 @@ public void shouldReportTooFewInvocationsInOrder() { Invocation invocation = new InvocationBuilder().simpleMethod().toInvocation(); Invocation invocationTwo = new InvocationBuilder().differentMethod().toInvocation(); - exception.expect(VerificationInOrderFailure.class); - exception.expectMessage("iMethods.simpleMethod()"); - exception.expectMessage("Wanted *at least* 2 times"); - exception.expectMessage("But was 1 time"); - // when - checkAtLeastNumberOfInvocations( - asList(invocation, invocationTwo), new InvocationMatcher(invocation), 2, context); + assertThatThrownBy( + () -> + checkAtLeastNumberOfInvocations( + asList(invocation, invocationTwo), + new InvocationMatcher(invocation), + 2, + context)) + .isInstanceOf(VerificationInOrderFailure.class) + .hasMessageContainingAll( + "iMethods.simpleMethod();", "Wanted *at least* 2 times", "But was 1 time"); } @Test @@ -76,13 +75,16 @@ public void shouldReportTooFewInvocations() { Invocation invocation = new InvocationBuilder().simpleMethod().toInvocation(); Invocation invocationTwo = new InvocationBuilder().differentMethod().toInvocation(); - exception.expect(TooFewActualInvocations.class); - exception.expectMessage("iMethods.simpleMethod()"); - exception.expectMessage("Wanted *at least* 2 times"); - exception.expectMessage("But was 1 time"); - // when - checkAtLeastNumberOfInvocations( - asList(invocation, invocationTwo), new InvocationMatcher(invocation), 2); + assertThatThrownBy( + () -> { + checkAtLeastNumberOfInvocations( + asList(invocation, invocationTwo), + new InvocationMatcher(invocation), + 2); + }) + .isInstanceOf(TooFewActualInvocations.class) + .hasMessageContainingAll( + "iMethods.simpleMethod();", "Wanted *at least* 2 times", "But was 1 time"); } } diff --git a/src/test/java/org/mockito/internal/verification/checkers/MissingInvocationCheckerTest.java b/src/test/java/org/mockito/internal/verification/checkers/MissingInvocationCheckerTest.java index 99c6a7af29..911a9a59ac 100644 --- a/src/test/java/org/mockito/internal/verification/checkers/MissingInvocationCheckerTest.java +++ b/src/test/java/org/mockito/internal/verification/checkers/MissingInvocationCheckerTest.java @@ -6,18 +6,21 @@ import static java.util.Arrays.asList; import static java.util.Collections.singletonList; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.ArrayList; import java.util.List; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentMatcher; import org.mockito.Mock; import org.mockito.exceptions.verification.WantedButNotInvoked; import org.mockito.exceptions.verification.opentest4j.ArgumentsAreDifferent; -import org.mockito.internal.invocation.*; +import org.mockito.internal.invocation.InterceptedInvocation; +import org.mockito.internal.invocation.InvocationBuilder; +import org.mockito.internal.invocation.InvocationMatcher; +import org.mockito.internal.invocation.MockitoMethod; +import org.mockito.internal.invocation.RealMethod; import org.mockito.internal.invocation.mockref.MockReference; import org.mockito.invocation.Invocation; import org.mockito.invocation.Location; @@ -31,8 +34,6 @@ public class MissingInvocationCheckerTest extends TestBase { @Mock private IMethods mock; - @Rule public ExpectedException exception = ExpectedException.none(); - @Test public void shouldPassBecauseActualInvocationFound() { wanted = buildSimpleMethod().toInvocationMatcher(); @@ -46,13 +47,16 @@ public void shouldReportWantedButNotInvoked() { wanted = buildSimpleMethod().toInvocationMatcher(); invocations = asList(buildDifferentMethod().toInvocation()); - exception.expect(WantedButNotInvoked.class); - exception.expectMessage("Wanted but not invoked:"); - exception.expectMessage("mock.simpleMethod()"); - exception.expectMessage("However, there was exactly 1 interaction with this mock:"); - exception.expectMessage("mock.differentMethod();"); - - MissingInvocationChecker.checkMissingInvocation(invocations, wanted); + assertThatThrownBy( + () -> { + MissingInvocationChecker.checkMissingInvocation(invocations, wanted); + }) + .isInstanceOf(WantedButNotInvoked.class) + .hasMessageContainingAll( + "Wanted but not invoked:", + "mock.simpleMethod()", + "However, there was exactly 1 interaction with this mock:", + "mock.differentMethod();"); } @Test @@ -60,14 +64,16 @@ public void shouldReportWantedInvocationDiffersFromActual() { wanted = buildIntArgMethod(new InvocationBuilder()).arg(2222).toInvocationMatcher(); invocations = asList(buildIntArgMethod(new InvocationBuilder()).arg(1111).toInvocation()); - exception.expect(ArgumentsAreDifferent.class); - - exception.expectMessage("Argument(s) are different! Wanted:"); - exception.expectMessage("mock.intArgumentMethod(2222);"); - exception.expectMessage("Actual invocations have different arguments:"); - exception.expectMessage("mock.intArgumentMethod(1111);"); - - MissingInvocationChecker.checkMissingInvocation(invocations, wanted); + assertThatThrownBy( + () -> { + MissingInvocationChecker.checkMissingInvocation(invocations, wanted); + }) + .isInstanceOf(ArgumentsAreDifferent.class) + .hasMessageContainingAll( + "Argument(s) are different! Wanted:", + "mock.intArgumentMethod(2222);", + "Actual invocations have different arguments:", + "mock.intArgumentMethod(1111);"); } @Test @@ -77,14 +83,16 @@ public void shouldReportUsingInvocationDescription() { singletonList( buildIntArgMethod(new CustomInvocationBuilder()).arg(1111).toInvocation()); - exception.expect(ArgumentsAreDifferent.class); - - exception.expectMessage("Argument(s) are different! Wanted:"); - exception.expectMessage("mock.intArgumentMethod(MyCoolPrint(2222));"); - exception.expectMessage("Actual invocations have different arguments:"); - exception.expectMessage("mock.intArgumentMethod(MyCoolPrint(1111));"); - - MissingInvocationChecker.checkMissingInvocation(invocations, wanted); + assertThatThrownBy( + () -> { + MissingInvocationChecker.checkMissingInvocation(invocations, wanted); + }) + .isInstanceOf(ArgumentsAreDifferent.class) + .hasMessageContainingAll( + "Argument(s) are different! Wanted:", + "mock.intArgumentMethod(MyCoolPrint(2222));", + "Actual invocations have different arguments:", + "mock.intArgumentMethod(MyCoolPrint(1111));"); } private InvocationBuilder buildIntArgMethod(InvocationBuilder invocationBuilder) { @@ -112,7 +120,7 @@ protected Invocation createInvocation( mockRef, mockitoMethod, arguments, realMethod, location, sequenceNumber) { @Override public List getArgumentsAsMatchers() { - List matchers = new ArrayList(); + List matchers = new ArrayList<>(); for (final Object argument : getRawArguments()) { matchers.add( new ArgumentMatcher() { diff --git a/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsCheckerTest.java b/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsCheckerTest.java index d1878fc2e5..1c9bc6df87 100644 --- a/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsCheckerTest.java +++ b/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsCheckerTest.java @@ -6,18 +6,15 @@ import static java.util.Arrays.asList; import static java.util.Collections.emptyList; - import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import java.util.Collections; import java.util.List; -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.hamcrest.TypeSafeMatcher; +import org.assertj.core.api.Condition; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.junit.rules.TestName; import org.junit.runner.RunWith; import org.mockito.Mock; @@ -39,55 +36,59 @@ public class NumberOfInvocationsCheckerTest { @Mock private IMethods mock; - @Rule public ExpectedException exception = ExpectedException.none(); - @Rule public TestName testName = new TestName(); @Test - public void shouldReportTooFewActual() throws Exception { + public void shouldReportTooFewActual() { wanted = buildSimpleMethod().toInvocationMatcher(); invocations = asList(buildSimpleMethod().toInvocation(), buildSimpleMethod().toInvocation()); - exception.expect(TooFewActualInvocations.class); - exception.expectMessage("mock.simpleMethod()"); - exception.expectMessage("Wanted 100 times"); - exception.expectMessage("But was 2 times"); - - NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 100); + assertThatThrownBy( + () -> { + NumberOfInvocationsChecker.checkNumberOfInvocations( + invocations, wanted, 100); + }) + .isInstanceOf(TooFewActualInvocations.class) + .hasMessageContainingAll( + "mock.simpleMethod()", "Wanted 100 times", "But was 2 times"); } @Test - public void shouldReportAllInvocationsStackTrace() throws Exception { + public void shouldReportAllInvocationsStackTrace() { wanted = buildSimpleMethod().toInvocationMatcher(); invocations = asList(buildSimpleMethod().toInvocation(), buildSimpleMethod().toInvocation()); - exception.expect(TooFewActualInvocations.class); - exception.expectMessage("mock.simpleMethod()"); - exception.expectMessage("Wanted 100 times"); - exception.expectMessage("But was 2 times"); - exception.expectMessage(containsTimes("-> at", 3)); - - NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 100); + assertThatThrownBy( + () -> { + NumberOfInvocationsChecker.checkNumberOfInvocations( + invocations, wanted, 100); + }) + .isInstanceOf(TooFewActualInvocations.class) + .hasMessageContainingAll( + "mock.simpleMethod()", "Wanted 100 times", "But was 2 times") + .has(messageContaining("-> at", 3)); } @Test - public void shouldNotReportWithLastInvocationStackTraceIfNoInvocationsFound() throws Exception { + public void shouldNotReportWithLastInvocationStackTraceIfNoInvocationsFound() { invocations = emptyList(); wanted = buildSimpleMethod().toInvocationMatcher(); - exception.expect(TooFewActualInvocations.class); - exception.expectMessage("mock.simpleMethod()"); - exception.expectMessage("Wanted 100 times"); - exception.expectMessage("But was 0 times"); - exception.expectMessage(containsTimes("-> at", 1)); - - NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 100); + assertThatThrownBy( + () -> { + NumberOfInvocationsChecker.checkNumberOfInvocations( + invocations, wanted, 100); + }) + .isInstanceOf(TooFewActualInvocations.class) + .hasMessageContainingAll( + "mock.simpleMethod()", "Wanted 100 times", "But was 0 times") + .has(messageContaining("-> at", 1)); } @Test - public void shouldReportWithAllInvocationsStackTrace() throws Exception { + public void shouldReportWithAllInvocationsStackTrace() { Invocation first = buildSimpleMethod().toInvocation(); Invocation second = buildSimpleMethod().toInvocation(); Invocation third = buildSimpleMethod().toInvocation(); @@ -95,61 +96,76 @@ public void shouldReportWithAllInvocationsStackTrace() throws Exception { invocations = asList(first, second, third); wanted = buildSimpleMethod().toInvocationMatcher(); - exception.expect(TooManyActualInvocations.class); - exception.expectMessage("" + first.getLocation()); - exception.expectMessage("" + second.getLocation()); - exception.expectMessage("" + third.getLocation()); - NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 2); + assertThatThrownBy( + () -> { + NumberOfInvocationsChecker.checkNumberOfInvocations( + invocations, wanted, 2); + }) + .isInstanceOf(TooManyActualInvocations.class) + .hasMessageContainingAll( + "" + first.getLocation(), + "" + second.getLocation(), + "" + third.getLocation()); } @Test - public void shouldReportTooManyActual() throws Exception { + public void shouldReportTooManyActual() { Invocation first = buildSimpleMethod().toInvocation(); Invocation second = buildSimpleMethod().toInvocation(); invocations = asList(first, second); wanted = buildSimpleMethod().toInvocationMatcher(); - exception.expectMessage("Wanted 1 time"); - exception.expectMessage("But was 2 times"); - - NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 1); + assertThatThrownBy( + () -> { + NumberOfInvocationsChecker.checkNumberOfInvocations( + invocations, wanted, 1); + }) + .hasMessageContainingAll("Wanted 1 time", "But was 2 times"); } @Test - public void shouldReportNeverWantedButInvokedWithArgs() throws Exception { + public void shouldReportNeverWantedButInvokedWithArgs() { Invocation invocation = buildSimpleMethodWithArgs("arg1").toInvocation(); invocations = Collections.singletonList(invocation); wanted = buildSimpleMethodWithArgs("arg1").toInvocationMatcher(); - exception.expect(NeverWantedButInvoked.class); - exception.expectMessage("Never wanted here"); - exception.expectMessage("But invoked here"); - exception.expectMessage("" + invocation.getLocation() + " with arguments: [arg1]"); - - NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 0); + assertThatThrownBy( + () -> { + NumberOfInvocationsChecker.checkNumberOfInvocations( + invocations, wanted, 0); + }) + .isInstanceOf(NeverWantedButInvoked.class) + .hasMessageContainingAll( + "Never wanted here", + "But invoked here", + "" + invocation.getLocation() + " with arguments: [arg1]"); } @Test - public void shouldReportNeverWantedButInvokedWithArgs_multipleInvocations() throws Exception { + public void shouldReportNeverWantedButInvokedWithArgs_multipleInvocations() { Invocation first = buildSimpleMethodWithArgs("arg1").toInvocation(); Invocation second = buildSimpleMethodWithArgs("arg1").toInvocation(); invocations = asList(first, second); wanted = buildSimpleMethodWithArgs("arg1").toInvocationMatcher(); - exception.expect(NeverWantedButInvoked.class); - exception.expectMessage("Never wanted here"); - exception.expectMessage("But invoked here"); - exception.expectMessage("" + first.getLocation() + " with arguments: [arg1]"); - exception.expectMessage("" + second.getLocation() + " with arguments: [arg1]"); - - NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 0); + assertThatThrownBy( + () -> { + NumberOfInvocationsChecker.checkNumberOfInvocations( + invocations, wanted, 0); + }) + .isInstanceOf(NeverWantedButInvoked.class) + .hasMessageContainingAll( + "Never wanted here", + "But invoked here", + "" + first.getLocation() + " with arguments: [arg1]", + "" + second.getLocation() + " with arguments: [arg1]"); } @Test - public void shouldMarkInvocationsAsVerified() throws Exception { + public void shouldMarkInvocationsAsVerified() { Invocation invocation = buildSimpleMethod().toInvocation(); assertThat(invocation.isVerified()).isFalse(); @@ -167,40 +183,35 @@ private InvocationBuilder buildSimpleMethodWithArgs(String arg) { return new InvocationBuilder().mock(mock).simpleMethod().args(arg); } - private InvocationBuilder buildDifferentMethodWithArgs(String arg) { - return new InvocationBuilder().mock(mock).differentMethod().args(arg); - } - - private static BaseMatcher containsTimes(String value, int amount) { - return new StringContainsNumberMatcher(value, amount); + private static Condition messageContaining( + String value, int amountOfOccurrences) { + return new ThrowableMessageContainsOccurrencesCondition(value, amountOfOccurrences); } - private static class StringContainsNumberMatcher extends TypeSafeMatcher { + private static class ThrowableMessageContainsOccurrencesCondition extends Condition { - private final String expected; + private final String value; + private final int expectedOccurrences; - private final int amount; + public ThrowableMessageContainsOccurrencesCondition(String value, int expectedOccurrences) { + this.value = value; + this.expectedOccurrences = expectedOccurrences; - StringContainsNumberMatcher(String expected, int amount) { - this.expected = expected; - this.amount = amount; + as("exactly %s occurrences of \"%s\"", expectedOccurrences, value); } - public boolean matchesSafely(String text) { + @Override + public boolean matches(Throwable ex) { int lastIndex = 0; int count = 0; while (lastIndex != -1) { - lastIndex = text.indexOf(expected, lastIndex); + lastIndex = ex.getMessage().indexOf(value, lastIndex); if (lastIndex != -1) { count++; - lastIndex += expected.length(); + lastIndex += value.length(); } } - return count == amount; - } - - public void describeTo(Description description) { - description.appendText("containing '" + expected + "' exactly " + amount + " times"); + return count == expectedOccurrences; } } } diff --git a/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderCheckerTest.java b/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderCheckerTest.java index aae3b812a2..06b36c4d5f 100644 --- a/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderCheckerTest.java +++ b/src/test/java/org/mockito/internal/verification/checkers/NumberOfInvocationsInOrderCheckerTest.java @@ -6,19 +6,15 @@ import static java.util.Arrays.asList; import static java.util.Collections.emptyList; - import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import java.util.List; -import org.hamcrest.BaseMatcher; -import org.hamcrest.Description; -import org.hamcrest.TypeSafeMatcher; +import org.assertj.core.api.Condition; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.exceptions.verification.VerificationInOrderFailure; import org.mockito.internal.invocation.InvocationBuilder; import org.mockito.internal.invocation.InvocationMatcher; @@ -35,8 +31,6 @@ public class NumberOfInvocationsInOrderCheckerTest { private IMethods mock; - @Rule public ExpectedException exception = ExpectedException.none(); - @Before public void setup() { context = new InOrderContextImpl(); @@ -52,30 +46,32 @@ public void shouldPassIfWantedIsZeroAndMatchingChunkIsEmpty() { } @Test - public void shouldPassIfChunkMatches() throws Exception { + public void shouldPassIfChunkMatches() { wanted = buildSimpleMethod().toInvocationMatcher(); invocations = asList(buildSimpleMethod().toInvocation()); NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 1, context); } @Test - public void shouldReportTooFewInvocations() throws Exception { + public void shouldReportTooFewInvocations() { Invocation first = buildSimpleMethod().toInvocation(); Invocation second = buildSimpleMethod().toInvocation(); wanted = buildSimpleMethod().toInvocationMatcher(); invocations = asList(first, second); - exception.expect(VerificationInOrderFailure.class); - exception.expectMessage("mock.simpleMethod()"); - exception.expectMessage("Wanted 4 times"); - exception.expectMessage("But was 2 times"); - - NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 4, context); + assertThatThrownBy( + () -> { + NumberOfInvocationsChecker.checkNumberOfInvocations( + invocations, wanted, 4, context); + }) + .isInstanceOf(VerificationInOrderFailure.class) + .hasMessageContainingAll( + "mock.simpleMethod()", "Wanted 4 times", "But was 2 times"); } @Test - public void shouldMarkAsVerifiedInOrder() throws Exception { + public void shouldMarkAsVerifiedInOrder() { Invocation invocation = buildSimpleMethod().toInvocation(); invocations = asList(invocation); @@ -87,50 +83,56 @@ public void shouldMarkAsVerifiedInOrder() throws Exception { } @Test - public void shouldReportTooFewActual() throws Exception { + public void shouldReportTooFewActual() { wanted = buildSimpleMethod().toInvocationMatcher(); invocations = asList(buildSimpleMethod().toInvocation(), buildSimpleMethod().toInvocation()); - exception.expect(VerificationInOrderFailure.class); - exception.expectMessage("mock.simpleMethod()"); - exception.expectMessage("Wanted 100 times"); - exception.expectMessage("But was 2 times"); - - NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 100, context); + assertThatThrownBy( + () -> { + NumberOfInvocationsChecker.checkNumberOfInvocations( + invocations, wanted, 100, context); + }) + .isInstanceOf(VerificationInOrderFailure.class) + .hasMessageContainingAll( + "mock.simpleMethod()", "Wanted 100 times", "But was 2 times"); } @Test - public void shouldReportWithAllInvocationsStackTrace() throws Exception { + public void shouldReportWithAllInvocationsStackTrace() { wanted = buildSimpleMethod().toInvocationMatcher(); invocations = asList(buildSimpleMethod().toInvocation(), buildSimpleMethod().toInvocation()); - exception.expect(VerificationInOrderFailure.class); - exception.expectMessage("mock.simpleMethod()"); - exception.expectMessage("Wanted 100 times"); - exception.expectMessage("But was 2 times"); - exception.expectMessage(containsTimes("-> at", 3)); - - NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 100, context); + assertThatThrownBy( + () -> { + NumberOfInvocationsChecker.checkNumberOfInvocations( + invocations, wanted, 100, context); + }) + .isInstanceOf(VerificationInOrderFailure.class) + .hasMessageContainingAll( + "mock.simpleMethod()", "Wanted 100 times", "But was 2 times") + .has(messageContaining("-> at", 3)); } @Test - public void shouldNotReportWithLastInvocationStackTraceIfNoInvocationsFound() throws Exception { + public void shouldNotReportWithLastInvocationStackTraceIfNoInvocationsFound() { invocations = emptyList(); wanted = buildSimpleMethod().toInvocationMatcher(); - exception.expect(VerificationInOrderFailure.class); - exception.expectMessage("mock.simpleMethod()"); - exception.expectMessage("Wanted 100 times"); - exception.expectMessage("But was 0 times"); - exception.expectMessage(containsTimes("-> at", 1)); - - NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 100, context); + assertThatThrownBy( + () -> { + NumberOfInvocationsChecker.checkNumberOfInvocations( + invocations, wanted, 100, context); + }) + .isInstanceOf(VerificationInOrderFailure.class) + .hasMessageContainingAll( + "mock.simpleMethod()", "Wanted 100 times", "But was 0 times") + .has(messageContaining("-> at", 1)); } @Test - public void shouldReportWithFirstUndesiredInvocationStackTrace() throws Exception { + public void shouldReportWithFirstUndesiredInvocationStackTrace() { Invocation first = buildSimpleMethod().toInvocation(); Invocation second = buildSimpleMethod().toInvocation(); Invocation third = buildSimpleMethod().toInvocation(); @@ -138,43 +140,54 @@ public void shouldReportWithFirstUndesiredInvocationStackTrace() throws Exceptio invocations = asList(first, second, third); wanted = buildSimpleMethod().toInvocationMatcher(); - exception.expect(VerificationInOrderFailure.class); - exception.expectMessage("" + third.getLocation()); - NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 2, context); + assertThatThrownBy( + () -> { + NumberOfInvocationsChecker.checkNumberOfInvocations( + invocations, wanted, 2, context); + }) + .isInstanceOf(VerificationInOrderFailure.class) + .hasMessageContaining("" + third.getLocation()); } @Test - public void shouldReportTooManyActual() throws Exception { + public void shouldReportTooManyActual() { Invocation first = buildSimpleMethod().toInvocation(); Invocation second = buildSimpleMethod().toInvocation(); invocations = asList(first, second); wanted = buildSimpleMethod().toInvocationMatcher(); - exception.expectMessage("Wanted 1 time"); - exception.expectMessage("But was 2 times"); - - NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 1, context); + assertThatThrownBy( + () -> { + NumberOfInvocationsChecker.checkNumberOfInvocations( + invocations, wanted, 1, context); + }) + .isInstanceOf(VerificationInOrderFailure.class) + .hasMessageContainingAll("Wanted 1 time", "But was 2 times"); } @Test - public void shouldReportNeverWantedButInvoked() throws Exception { + public void shouldReportNeverWantedButInvoked() { Invocation first = buildSimpleMethod().toInvocation(); invocations = asList(first); wanted = buildSimpleMethod().toInvocationMatcher(); - exception.expect(VerificationInOrderFailure.class); - exception.expectMessage("mock.simpleMethod()"); - exception.expectMessage("Wanted 0 times"); - exception.expectMessage("But was 1 time:"); - exception.expectMessage("" + first.getLocation()); - - NumberOfInvocationsChecker.checkNumberOfInvocations(invocations, wanted, 0, context); + assertThatThrownBy( + () -> { + NumberOfInvocationsChecker.checkNumberOfInvocations( + invocations, wanted, 0, context); + }) + .isInstanceOf(VerificationInOrderFailure.class) + .hasMessageContainingAll( + "mock.simpleMethod()", + "Wanted 0 times", + "But was 1 time:", + "" + first.getLocation()); } @Test - public void shouldMarkInvocationsAsVerified() throws Exception { + public void shouldMarkInvocationsAsVerified() { Invocation invocation = buildSimpleMethod().toInvocation(); assertThat(invocation.isVerified()).isFalse(); @@ -184,38 +197,35 @@ public void shouldMarkInvocationsAsVerified() throws Exception { assertThat(invocation.isVerified()).isTrue(); } - private static BaseMatcher containsTimes(String value, int amount) { - return new StringContainsNumberMatcher(value, amount); + private static Condition messageContaining( + String value, int amountOfOccurrences) { + return new ThrowableMessageContainsOccurrencesCondition(value, amountOfOccurrences); } - private static class StringContainsNumberMatcher extends TypeSafeMatcher { + private static class ThrowableMessageContainsOccurrencesCondition extends Condition { - private final String expected; + private final String value; + private final int expectedOccurrences; - private final int amount; + public ThrowableMessageContainsOccurrencesCondition(String value, int expectedOccurrences) { + this.value = value; + this.expectedOccurrences = expectedOccurrences; - StringContainsNumberMatcher(String expected, int amount) { - this.expected = expected; - this.amount = amount; + as("exactly %s occurrences of \"%s\"", expectedOccurrences, value); } @Override - public boolean matchesSafely(String text) { + public boolean matches(Throwable ex) { int lastIndex = 0; int count = 0; while (lastIndex != -1) { - lastIndex = text.indexOf(expected, lastIndex); + lastIndex = ex.getMessage().indexOf(value, lastIndex); if (lastIndex != -1) { count++; - lastIndex += expected.length(); + lastIndex += value.length(); } } - return count == amount; - } - - @Override - public void describeTo(Description description) { - description.appendText("containing '" + expected + "' exactly " + amount + " times"); + return count == expectedOccurrences; } } diff --git a/src/test/java/org/mockito/verification/NegativeDurationTest.java b/src/test/java/org/mockito/verification/NegativeDurationTest.java index 79530081cf..06b3cb4788 100644 --- a/src/test/java/org/mockito/verification/NegativeDurationTest.java +++ b/src/test/java/org/mockito/verification/NegativeDurationTest.java @@ -4,26 +4,31 @@ */ package org.mockito.verification; -import org.junit.Rule; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.Mockito; import org.mockito.exceptions.misusing.FriendlyReminderException; public class NegativeDurationTest { - @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void should_throw_exception_when_duration_is_negative_for_timeout_method() { - expectedException.expect(FriendlyReminderException.class); - expectedException.expectMessage("Don't panic! I'm just a friendly reminder!"); - Mockito.timeout(-1); + assertThatThrownBy( + () -> { + Mockito.timeout(-1); + }) + .isInstanceOf(FriendlyReminderException.class) + .hasMessageContaining("Don't panic! I'm just a friendly reminder!"); } @Test public void should_throw_exception_when_duration_is_negative_for_after_method() { - expectedException.expect(FriendlyReminderException.class); - expectedException.expectMessage("Don't panic! I'm just a friendly reminder!"); - Mockito.after(-1); + assertThatThrownBy( + () -> { + Mockito.after(-1); + }) + .isInstanceOf(FriendlyReminderException.class) + .hasMessageContaining("Don't panic! I'm just a friendly reminder!"); } } diff --git a/src/test/java/org/mockitousage/annotation/MockInjectionUsingConstructorTest.java b/src/test/java/org/mockitousage/annotation/MockInjectionUsingConstructorTest.java index 3a89fd3c67..c45c90ae2f 100644 --- a/src/test/java/org/mockitousage/annotation/MockInjectionUsingConstructorTest.java +++ b/src/test/java/org/mockitousage/annotation/MockInjectionUsingConstructorTest.java @@ -5,7 +5,11 @@ package org.mockitousage.annotation; import static org.assertj.core.api.Assertions.assertThat; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +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.mockito.Mockito.when; import static org.mockito.MockitoAnnotations.openMocks; @@ -16,10 +20,8 @@ import org.junit.Before; import org.junit.Ignore; -import org.junit.Rule; import org.junit.Test; import org.junit.internal.TextListener; -import org.junit.rules.ExpectedException; import org.junit.runner.JUnitCore; import org.junit.runner.RunWith; import org.mockito.InjectMocks; @@ -42,8 +44,6 @@ public class MockInjectionUsingConstructorTest { @InjectMocks private ArticleManager articleManager; @Spy @InjectMocks private ArticleManager spiedArticleManager; - @Rule public ExpectedException exception = ExpectedException.none(); - @Before public void before() { MockitoAnnotations.openMocks(this); @@ -54,11 +54,15 @@ public void shouldNotFailWhenNotInitialized() { assertNotNull(articleManager); } - @Test(expected = IllegalArgumentException.class) + @Test public void innerMockShouldRaiseAnExceptionThatChangesOuterMockBehavior() { when(calculator.countArticles("new")).thenThrow(new IllegalArgumentException()); - articleManager.updateArticleCounters("new"); + assertThatThrownBy( + () -> { + articleManager.updateArticleCounters("new"); + }) + .isInstanceOf(IllegalArgumentException.class); } @Test @@ -138,16 +142,18 @@ private static class ATest { } @Test - public void injectMocksMustFailWithInterface() throws Exception { + public void injectMocksMustFailWithInterface() { class TestCase { @InjectMocks IMethods f; } - exception.expect(MockitoException.class); - exception.expectMessage( - "Cannot instantiate @InjectMocks field named 'f'! Cause: the type 'IMethods' is an interface"); - - openMocks(new TestCase()); + assertThatThrownBy( + () -> { + openMocks(new TestCase()); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining( + "Cannot instantiate @InjectMocks field named 'f'! Cause: the type 'IMethods' is an interface"); } @Test @@ -156,45 +162,51 @@ class TestCase { @InjectMocks TimeUnit f; } - exception.expect(MockitoException.class); - exception.expectMessage( - "Cannot instantiate @InjectMocks field named 'f'! Cause: the type 'TimeUnit' is an enum"); - - openMocks(new TestCase()); + assertThatThrownBy( + () -> { + openMocks(new TestCase()); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining( + "Cannot instantiate @InjectMocks field named 'f'! Cause: the type 'TimeUnit' is an enum"); } @Test - public void injectMocksMustFailWithAbstractClass() throws Exception { + public void injectMocksMustFailWithAbstractClass() { class TestCase { @InjectMocks AbstractCollection f; } - exception.expect(MockitoException.class); - exception.expectMessage( - "Cannot instantiate @InjectMocks field named 'f'! Cause: the type 'AbstractCollection' is an abstract class"); - - openMocks(new TestCase()); + assertThatThrownBy( + () -> { + openMocks(new TestCase()); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining( + "Cannot instantiate @InjectMocks field named 'f'! Cause: the type 'AbstractCollection' is an abstract class"); } @Test - public void injectMocksMustFailWithNonStaticInnerClass() throws Exception { + public void injectMocksMustFailWithNonStaticInnerClass() { class TestCase { class InnerClass {} @InjectMocks InnerClass f; } - exception.expect(MockitoException.class); - exception.expectMessage( - "Cannot instantiate @InjectMocks field named 'f'! Cause: the type 'InnerClass' is an inner non static class"); - - openMocks(new TestCase()); + assertThatThrownBy( + () -> { + openMocks(new TestCase()); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining( + "Cannot instantiate @InjectMocks field named 'f'! Cause: the type 'InnerClass' is an inner non static class"); } static class StaticInnerClass {} @Test - public void injectMocksMustSucceedWithStaticInnerClass() throws Exception { + public void injectMocksMustSucceedWithStaticInnerClass() { class TestCase { @InjectMocks StaticInnerClass f; } @@ -206,7 +218,7 @@ class TestCase { } @Test - public void injectMocksMustSucceedWithInstance() throws Exception { + public void injectMocksMustSucceedWithInstance() { class TestCase { @InjectMocks StaticInnerClass f = new StaticInnerClass(); } diff --git a/src/test/java/org/mockitousage/annotation/SpyAnnotationTest.java b/src/test/java/org/mockitousage/annotation/SpyAnnotationTest.java index 8db8ef1d5a..01edd3c687 100644 --- a/src/test/java/org/mockitousage/annotation/SpyAnnotationTest.java +++ b/src/test/java/org/mockitousage/annotation/SpyAnnotationTest.java @@ -5,6 +5,7 @@ package org.mockitousage.annotation; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -162,9 +163,13 @@ String fullStrength() { assertEquals("inner strength", outer.strength.fullStrength()); } - @Test(expected = IndexOutOfBoundsException.class) + @Test public void should_reset_spy() throws Exception { - spiedList.get(10); // see shouldInitSpy + assertThatThrownBy( + () -> { + spiedList.get(10); // see shouldInitSpy + }) + .isInstanceOf(IndexOutOfBoundsException.class); } @Test diff --git a/src/test/java/org/mockitousage/annotation/WrongSetOfAnnotationsTest.java b/src/test/java/org/mockitousage/annotation/WrongSetOfAnnotationsTest.java index f5bf525249..a2b1560e1a 100644 --- a/src/test/java/org/mockitousage/annotation/WrongSetOfAnnotationsTest.java +++ b/src/test/java/org/mockitousage/annotation/WrongSetOfAnnotationsTest.java @@ -4,6 +4,7 @@ */ package org.mockitousage.annotation; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import java.util.List; @@ -16,16 +17,23 @@ public class WrongSetOfAnnotationsTest extends TestBase { - @Test(expected = MockitoException.class) - public void should_not_allow_Mock_and_Spy() throws Exception { - MockitoAnnotations.openMocks( - new Object() { - @Mock @Spy List mock; - }); + @Test + public void should_not_allow_Mock_and_Spy() { + assertThatThrownBy( + () -> { + MockitoAnnotations.openMocks( + new Object() { + @Mock @Spy List mock; + }); + }) + .isInstanceOf(MockitoException.class) + .hasMessage( + "This combination of annotations is not permitted on a single field:\n" + + "@Spy and @Mock"); } @Test - public void should_not_allow_Spy_and_InjectMocks_on_interfaces() throws Exception { + public void should_not_allow_Spy_and_InjectMocks_on_interfaces() { try { MockitoAnnotations.openMocks( new Object() { @@ -38,7 +46,7 @@ public void should_not_allow_Spy_and_InjectMocks_on_interfaces() throws Exceptio } @Test - public void should_allow_Spy_and_InjectMocks() throws Exception { + public void should_allow_Spy_and_InjectMocks() { MockitoAnnotations.openMocks( new Object() { @InjectMocks @Spy WithDependency mock; @@ -49,35 +57,64 @@ static class WithDependency { List list; } - @Test(expected = MockitoException.class) - public void should_not_allow_Mock_and_InjectMocks() throws Exception { - MockitoAnnotations.openMocks( - new Object() { - @InjectMocks @Mock List mock; - }); + @Test + public void should_not_allow_Mock_and_InjectMocks() { + assertThatThrownBy( + () -> { + MockitoAnnotations.openMocks( + new Object() { + @InjectMocks @Mock List mock; + }); + }) + .isInstanceOf(MockitoException.class) + .hasMessage( + "This combination of annotations is not permitted on a single field:\n" + + "@Mock and @InjectMocks"); } - @Test(expected = MockitoException.class) - public void should_not_allow_Captor_and_Mock() throws Exception { - MockitoAnnotations.openMocks( - new Object() { - @Mock @Captor ArgumentCaptor captor; - }); + @Test + public void should_not_allow_Captor_and_Mock() { + assertThatThrownBy( + () -> { + MockitoAnnotations.openMocks( + new Object() { + @Mock @Captor ArgumentCaptor captor; + }); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "You cannot have more than one Mockito annotation on a field!", + "The field 'captor' has multiple Mockito annotations.", + "For info how to use annotations see examples in javadoc for MockitoAnnotations class."); } - @Test(expected = MockitoException.class) - public void should_not_allow_Captor_and_Spy() throws Exception { - MockitoAnnotations.openMocks( - new Object() { - @Spy @Captor ArgumentCaptor captor; - }); + @Test + public void should_not_allow_Captor_and_Spy() { + assertThatThrownBy( + () -> { + MockitoAnnotations.openMocks( + new Object() { + @Spy @Captor ArgumentCaptor captor; + }); + }) + .isInstanceOf(MockitoException.class) + .hasMessage( + "This combination of annotations is not permitted on a single field:\n" + + "@Spy and @Captor"); } - @Test(expected = MockitoException.class) - public void should_not_allow_Captor_and_InjectMocks() throws Exception { - MockitoAnnotations.openMocks( - new Object() { - @InjectMocks @Captor ArgumentCaptor captor; - }); + @Test + public void should_not_allow_Captor_and_InjectMocks() { + assertThatThrownBy( + () -> { + MockitoAnnotations.openMocks( + new Object() { + @InjectMocks @Captor ArgumentCaptor captor; + }); + }) + .isInstanceOf(MockitoException.class) + .hasMessage( + "This combination of annotations is not permitted on a single field:\n" + + "@Captor and @InjectMocks"); } } diff --git a/src/test/java/org/mockitousage/basicapi/ResetInvocationsTest.java b/src/test/java/org/mockitousage/basicapi/ResetInvocationsTest.java index e6f2caf8d6..580f055760 100644 --- a/src/test/java/org/mockitousage/basicapi/ResetInvocationsTest.java +++ b/src/test/java/org/mockitousage/basicapi/ResetInvocationsTest.java @@ -4,8 +4,12 @@ */ package org.mockitousage.basicapi; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.clearInvocations; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; import org.junit.Test; import org.mockito.Mock; @@ -42,13 +46,23 @@ public void should_reset_invocations_on_multiple_mocks() { verifyNoMoreInteractions(methods, moarMethods); } - @Test(expected = NotAMockException.class) + @Test public void resettingNonMockIsSafe() { - clearInvocations(""); + assertThatThrownBy( + () -> { + clearInvocations(""); + }) + .isInstanceOf(NotAMockException.class) + .hasMessage("Argument should be a mock, but is: class java.lang.String"); } - @Test(expected = NotAMockException.class) + @Test public void resettingNullIsSafe() { - clearInvocations(new Object[] {null}); + assertThatThrownBy( + () -> { + clearInvocations(new Object[] {null}); + }) + .isInstanceOf(NotAMockException.class) + .hasMessage("Argument should be a mock, but is null!"); } } diff --git a/src/test/java/org/mockitousage/basicapi/ResetTest.java b/src/test/java/org/mockitousage/basicapi/ResetTest.java index 95f4730f70..72db5c7101 100644 --- a/src/test/java/org/mockitousage/basicapi/ResetTest.java +++ b/src/test/java/org/mockitousage/basicapi/ResetTest.java @@ -5,6 +5,7 @@ package org.mockitousage.basicapi; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.*; import static org.mockito.Mockito.*; @@ -33,18 +34,28 @@ public void shouldResetOngoingStubbingSoThatMoreMeaningfulExceptionsAreRaised() } } - @Test(expected = NotAMockException.class) + @Test public void resettingNonMockIsSafe() { - reset(""); + assertThatThrownBy( + () -> { + reset(""); + }) + .isInstanceOf(NotAMockException.class) + .hasMessage("Argument should be a mock, but is: class java.lang.String"); } - @Test(expected = NotAMockException.class) + @Test public void resettingNullIsSafe() { - reset(new Object[] {null}); + assertThatThrownBy( + () -> { + reset(new Object[] {null}); + }) + .isInstanceOf(NotAMockException.class) + .hasMessage("Argument should be a mock, but is null!"); } @Test - public void shouldRemoveAllStubbing() throws Exception { + public void shouldRemoveAllStubbing() { when(mock.objectReturningMethod(isA(Integer.class))).thenReturn(100); when(mock.objectReturningMethod(200)).thenReturn(200); reset(mock); @@ -54,21 +65,21 @@ public void shouldRemoveAllStubbing() throws Exception { } @Test - public void shouldRemoveAllInteractions() throws Exception { + public void shouldRemoveAllInteractions() { mock.simpleMethod(1); reset(mock); verifyNoInteractions(mock); } @Test - public void shouldRemoveAllInteractionsVerifyNoInteractions() throws Exception { + public void shouldRemoveAllInteractionsVerifyNoInteractions() { mock.simpleMethod(1); reset(mock); verifyNoInteractions(mock); } @Test - public void shouldRemoveStubbingToString() throws Exception { + public void shouldRemoveStubbingToString() { IMethods mockTwo = mock(IMethods.class); when(mockTwo.toString()).thenReturn("test"); reset(mockTwo); diff --git a/src/test/java/org/mockitousage/bugs/AtLeastMarksAllInvocationsVerified.java b/src/test/java/org/mockitousage/bugs/AtLeastMarksAllInvocationsVerified.java index fc582ee4c2..2c231e06f6 100644 --- a/src/test/java/org/mockitousage/bugs/AtLeastMarksAllInvocationsVerified.java +++ b/src/test/java/org/mockitousage/bugs/AtLeastMarksAllInvocationsVerified.java @@ -4,9 +4,14 @@ */ package org.mockitousage.bugs; -import static org.mockito.Mockito.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; import org.junit.Test; +import org.mockito.exceptions.verification.NoInteractionsWanted; import org.mockitoutil.TestBase; // see issue 112 @@ -18,7 +23,7 @@ public void allowedMethod() {} public void disallowedMethod() {} } - @Test(expected = org.mockito.exceptions.verification.NoInteractionsWanted.class) + @Test public void shouldFailBecauseDisallowedMethodWasCalled() { SomeMethods someMethods = mock(SomeMethods.class); @@ -26,6 +31,18 @@ public void shouldFailBecauseDisallowedMethodWasCalled() { someMethods.disallowedMethod(); verify(someMethods, atLeast(1)).allowedMethod(); - verifyNoMoreInteractions(someMethods); + assertThatThrownBy( + () -> { + verifyNoMoreInteractions(someMethods); + }) + .isInstanceOf(NoInteractionsWanted.class) + .hasMessageContainingAll( + "No interactions wanted here:", + "-> at ", + "But found this interaction on mock 'someMethods':", + "-> at ", + "For your reference, here is the list of all invocations ([?] - means unverified).", + "1. -> at ", + "2. [?]-> at "); } } diff --git a/src/test/java/org/mockitousage/bugs/ClassCastExOnVerifyZeroInteractionsTest.java b/src/test/java/org/mockitousage/bugs/ClassCastExOnVerifyZeroInteractionsTest.java index 060aa04cd0..a22ae24539 100644 --- a/src/test/java/org/mockitousage/bugs/ClassCastExOnVerifyZeroInteractionsTest.java +++ b/src/test/java/org/mockitousage/bugs/ClassCastExOnVerifyZeroInteractionsTest.java @@ -4,13 +4,13 @@ */ package org.mockitousage.bugs; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verifyNoInteractions; import org.junit.Test; import org.mockito.exceptions.misusing.WrongTypeOfReturnValue; import org.mockito.exceptions.verification.NoInteractionsWanted; -import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; public class ClassCastExOnVerifyZeroInteractionsTest { @@ -18,31 +18,35 @@ public interface TestMock { boolean m1(); } - @Test(expected = NoInteractionsWanted.class) + @Test public void should_not_throw_ClassCastException_when_mock_verification_fails() { - TestMock test = - mock( - TestMock.class, - new Answer() { - public Object answer(InvocationOnMock invocation) throws Throwable { - return false; - } - }); + TestMock test = mock(TestMock.class, (Answer) invocation -> false); test.m1(); - verifyNoInteractions(test); + + assertThatThrownBy( + () -> { + verifyNoInteractions(test); + }) + .isInstanceOf(NoInteractionsWanted.class) + .hasMessageContainingAll( + "No interactions wanted here:", + "But found these interactions on mock 'testMock':", + "Actually, above is the only interaction with this mock."); } - @Test(expected = WrongTypeOfReturnValue.class) - public void should_report_bogus_default_answer() throws Exception { - TestMock test = - mock( - TestMock.class, - new Answer() { - public Object answer(InvocationOnMock invocation) throws Throwable { - return false; - } - }); + @Test + public void should_report_bogus_default_answer() { + TestMock test = mock(TestMock.class, (Answer) invocation -> false); - String ignored = test.toString(); + assertThatThrownBy( + () -> { + String ignored = test.toString(); + }) + .isInstanceOf(WrongTypeOfReturnValue.class) + .hasMessageContainingAll( + "Default answer returned a result with the wrong type:", + "Boolean cannot be returned by toString()", + "toString() should return String", + "The default answer of testMock that was configured on the mock is probably incorrectly implemented."); } } diff --git a/src/test/java/org/mockitousage/bugs/NPEWithCertainMatchersTest.java b/src/test/java/org/mockitousage/bugs/NPEWithCertainMatchersTest.java index 108f5f114b..80703202c5 100644 --- a/src/test/java/org/mockitousage/bugs/NPEWithCertainMatchersTest.java +++ b/src/test/java/org/mockitousage/bugs/NPEWithCertainMatchersTest.java @@ -4,6 +4,7 @@ */ package org.mockitousage.bugs; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.*; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; @@ -51,17 +52,35 @@ public void shouldNotThrowNPEWhenIntegerPassedToSame() { verify(mock, never()).intArgumentMethod(same(new Integer(100))); } - @Test(expected = AssertionError.class) + @Test public void shouldNotThrowNPEWhenNullPassedToEq() { mock.objectArgMethod("not null"); - verify(mock).objectArgMethod(eq(null)); + assertThatThrownBy( + () -> { + verify(mock).objectArgMethod(eq(null)); + }) + .isInstanceOf(AssertionError.class) + .hasMessageContainingAll( + "Argument(s) are different! Wanted:", + "mock.objectArgMethod(null);", + "Actual invocations have different arguments:", + "mock.objectArgMethod(\"not null\");"); } - @Test(expected = AssertionError.class) + @Test public void shouldNotThrowNPEWhenNullPassedToSame() { mock.objectArgMethod("not null"); - verify(mock).objectArgMethod(same(null)); + assertThatThrownBy( + () -> { + verify(mock).objectArgMethod(same(null)); + }) + .isInstanceOf(AssertionError.class) + .hasMessageContainingAll( + "Argument(s) are different! Wanted:", + "mock.objectArgMethod(same(null));", + "Actual invocations have different arguments:", + "mock.objectArgMethod(\"not null\");"); } } diff --git a/src/test/java/org/mockitousage/customization/BDDMockitoTest.java b/src/test/java/org/mockitousage/customization/BDDMockitoTest.java index db29117be6..89f85fbf5b 100644 --- a/src/test/java/org/mockitousage/customization/BDDMockitoTest.java +++ b/src/test/java/org/mockitousage/customization/BDDMockitoTest.java @@ -4,12 +4,23 @@ */ package org.mockitousage.customization; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; -import static org.mockito.BDDMockito.*; +import static org.mockito.BDDMockito.anyString; +import static org.mockito.BDDMockito.given; +import static org.mockito.BDDMockito.inOrder; +import static org.mockito.BDDMockito.mock; +import static org.mockito.BDDMockito.then; +import static org.mockito.BDDMockito.times; +import static org.mockito.BDDMockito.willAnswer; +import static org.mockito.BDDMockito.willCallRealMethod; +import static org.mockito.BDDMockito.willDoNothing; +import static org.mockito.BDDMockito.willReturn; +import static org.mockito.BDDMockito.willThrow; import java.util.Set; -import org.assertj.core.api.Assertions; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mock; @@ -17,7 +28,6 @@ import org.mockito.exceptions.verification.NoInteractionsWanted; import org.mockito.exceptions.verification.VerificationInOrderFailure; import org.mockito.exceptions.verification.WantedButNotInvoked; -import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.mockitousage.IMethods; import org.mockitousage.MethodsImpl; @@ -28,30 +38,30 @@ public class BDDMockitoTest extends TestBase { @Mock IMethods mock; @Test - public void should_stub() throws Exception { + public void should_stub() { given(mock.simpleMethod("foo")).willReturn("bar"); - Assertions.assertThat(mock.simpleMethod("foo")).isEqualTo("bar"); - Assertions.assertThat(mock.simpleMethod("whatever")).isEqualTo(null); + assertThat(mock.simpleMethod("foo")).isEqualTo("bar"); + assertThat(mock.simpleMethod("whatever")).isNull(); } @Test - public void should_stub_with_throwable() throws Exception { + public void should_stub_with_throwable() { given(mock.simpleMethod("foo")).willThrow(new SomethingWasWrong()); try { - Assertions.assertThat(mock.simpleMethod("foo")).isEqualTo("foo"); + assertThat(mock.simpleMethod("foo")).isEqualTo("foo"); fail(); } catch (SomethingWasWrong expected) { } } @Test - public void should_stub_with_throwable_class() throws Exception { + public void should_stub_with_throwable_class() { given(mock.simpleMethod("foo")).willThrow(SomethingWasWrong.class); try { - Assertions.assertThat(mock.simpleMethod("foo")).isEqualTo("foo"); + assertThat(mock.simpleMethod("foo")).isEqualTo("foo"); fail(); } catch (SomethingWasWrong expected) { } @@ -59,73 +69,71 @@ public void should_stub_with_throwable_class() throws Exception { @Test @SuppressWarnings("unchecked") - public void should_stub_with_throwable_classes() throws Exception { + public void should_stub_with_throwable_classes() { // unavoidable 'unchecked generic array creation' warning (from JDK7 onward) given(mock.simpleMethod("foo")) .willThrow(SomethingWasWrong.class, AnotherThingWasWrong.class); try { - Assertions.assertThat(mock.simpleMethod("foo")).isEqualTo("foo"); + assertThat(mock.simpleMethod("foo")).isEqualTo("foo"); fail(); } catch (SomethingWasWrong expected) { } } @Test - public void should_stub_with_answer() throws Exception { + public void should_stub_with_answer() { given(mock.simpleMethod(anyString())) .willAnswer( - new Answer() { - public String answer(InvocationOnMock invocation) throws Throwable { - return invocation.getArgument(0); - } - }); + (Answer) + invocation -> { + return invocation.getArgument(0); + }); - Assertions.assertThat(mock.simpleMethod("foo")).isEqualTo("foo"); + assertThat(mock.simpleMethod("foo")).isEqualTo("foo"); } @Test - public void should_stub_with_will_answer_alias() throws Exception { + public void should_stub_with_will_answer_alias() { given(mock.simpleMethod(anyString())) .will( - new Answer() { - public String answer(InvocationOnMock invocation) throws Throwable { - return invocation.getArgument(0); - } - }); + (Answer) + invocation -> { + return invocation.getArgument(0); + }); - Assertions.assertThat(mock.simpleMethod("foo")).isEqualTo("foo"); + assertThat(mock.simpleMethod("foo")).isEqualTo("foo"); } @Test - public void should_stub_consecutively() throws Exception { + public void should_stub_consecutively() { given(mock.simpleMethod(anyString())).willReturn("foo").willReturn("bar"); - Assertions.assertThat(mock.simpleMethod("whatever")).isEqualTo("foo"); - Assertions.assertThat(mock.simpleMethod("whatever")).isEqualTo("bar"); + assertThat(mock.simpleMethod("whatever")).isEqualTo("foo"); + assertThat(mock.simpleMethod("whatever")).isEqualTo("bar"); } @Test - public void should_return_consecutively() throws Exception { + public void should_return_consecutively() { given(mock.objectReturningMethodNoArgs()).willReturn("foo", "bar", 12L, new byte[0]); - Assertions.assertThat(mock.objectReturningMethodNoArgs()).isEqualTo("foo"); - Assertions.assertThat(mock.objectReturningMethodNoArgs()).isEqualTo("bar"); - Assertions.assertThat(mock.objectReturningMethodNoArgs()).isEqualTo(12L); - Assertions.assertThat(mock.objectReturningMethodNoArgs()).isEqualTo(new byte[0]); + assertThat(mock.objectReturningMethodNoArgs()).isEqualTo("foo"); + assertThat(mock.objectReturningMethodNoArgs()).isEqualTo("bar"); + assertThat(mock.objectReturningMethodNoArgs()).isEqualTo(12L); + assertThat(mock.objectReturningMethodNoArgs()).isEqualTo(new byte[0]); } @Test - public void should_stub_consecutively_with_call_real_method() throws Exception { + public void should_stub_consecutively_with_call_real_method() { MethodsImpl mock = mock(MethodsImpl.class); willReturn("foo").willCallRealMethod().given(mock).simpleMethod(); - Assertions.assertThat(mock.simpleMethod()).isEqualTo("foo"); - Assertions.assertThat(mock.simpleMethod()).isEqualTo(null); + assertThat(mock.simpleMethod()).isEqualTo("foo"); + assertThat(mock.simpleMethod()).isNull(); } @Test - public void should_stub_void() throws Exception { + public void should_stub_void() { willThrow(new SomethingWasWrong()).given(mock).voidMethod(); try { @@ -136,7 +144,7 @@ public void should_stub_void() throws Exception { } @Test - public void should_stub_void_with_exception_class() throws Exception { + public void should_stub_void_with_exception_class() { willThrow(SomethingWasWrong.class).given(mock).voidMethod(); try { @@ -148,7 +156,7 @@ public void should_stub_void_with_exception_class() throws Exception { @Test @SuppressWarnings("unchecked") - public void should_stub_void_with_exception_classes() throws Exception { + public void should_stub_void_with_exception_classes() { willThrow(SomethingWasWrong.class, AnotherThingWasWrong.class).given(mock).voidMethod(); try { @@ -159,7 +167,7 @@ public void should_stub_void_with_exception_classes() throws Exception { } @Test - public void should_stub_void_consecutively() throws Exception { + public void should_stub_void_consecutively() { willDoNothing().willThrow(new SomethingWasWrong()).given(mock).voidMethod(); mock.voidMethod(); @@ -171,7 +179,7 @@ public void should_stub_void_consecutively() throws Exception { } @Test - public void should_stub_void_consecutively_with_exception_class() throws Exception { + public void should_stub_void_consecutively_with_exception_class() { willDoNothing().willThrow(SomethingWasWrong.class).given(mock).voidMethod(); mock.voidMethod(); @@ -183,75 +191,110 @@ public void should_stub_void_consecutively_with_exception_class() throws Excepti } @Test - public void should_stub_using_do_return_style() throws Exception { + public void should_stub_using_do_return_style() { willReturn("foo").given(mock).simpleMethod("bar"); - Assertions.assertThat(mock.simpleMethod("boooo")).isEqualTo(null); - Assertions.assertThat(mock.simpleMethod("bar")).isEqualTo("foo"); + assertThat(mock.simpleMethod("boooo")).isEqualTo(null); + assertThat(mock.simpleMethod("bar")).isEqualTo("foo"); } @Test - public void should_stub_using_do_answer_style() throws Exception { + public void should_stub_using_do_answer_style() { willAnswer( - new Answer() { - public String answer(InvocationOnMock invocation) throws Throwable { - return invocation.getArgument(0); - } - }) + (Answer) + invocation -> { + return invocation.getArgument(0); + }) .given(mock) .simpleMethod(anyString()); - Assertions.assertThat(mock.simpleMethod("foo")).isEqualTo("foo"); + assertThat(mock.simpleMethod("foo")).isEqualTo("foo"); } @Test - public void should_stub_by_delegating_to_real_method() throws Exception { + public void should_stub_by_delegating_to_real_method() { // given Dog dog = mock(Dog.class); // when willCallRealMethod().given(dog).bark(); // then - Assertions.assertThat(dog.bark()).isEqualTo("woof"); + assertThat(dog.bark()).isEqualTo("woof"); } @Test - public void should_stub_by_delegating_to_real_method_using_typical_stubbing_syntax() - throws Exception { + public void should_stub_by_delegating_to_real_method_using_typical_stubbing_syntax() { // given Dog dog = mock(Dog.class); // when given(dog.bark()).willCallRealMethod(); // then - Assertions.assertThat(dog.bark()).isEqualTo("woof"); + assertThat(dog.bark()).isEqualTo("woof"); } @Test - public void should_all_stubbed_mock_reference_access() throws Exception { + public void should_all_stubbed_mock_reference_access() { Set expectedMock = mock(Set.class); Set returnedMock = given(expectedMock.isEmpty()).willReturn(false).getMock(); - Assertions.assertThat(returnedMock).isEqualTo(expectedMock); + assertThat(returnedMock).isEqualTo(expectedMock); } - @Test(expected = NotAMockException.class) + @Test public void should_validate_mock_when_verifying() { - then("notMock").should(); + assertThatThrownBy( + () -> { + then("notMock").should(); + }) + .isInstanceOf(NotAMockException.class) + .hasMessageContainingAll( + "Argument passed to verify() is of type String and is not a mock!", + "Make sure you place the parenthesis correctly!", + "See the examples of correct verifications:", + " verify(mock).someMethod();", + " verify(mock, times(10)).someMethod();", + " verify(mock, atLeastOnce()).someMethod();"); } - @Test(expected = NotAMockException.class) + @Test public void should_validate_mock_when_verifying_with_expected_number_of_invocations() { - then("notMock").should(times(19)); + assertThatThrownBy( + () -> { + then("notMock").should(times(19)); + }) + .isInstanceOf(NotAMockException.class) + .hasMessageContainingAll( + "Argument passed to verify() is of type String and is not a mock!", + "Make sure you place the parenthesis correctly!", + "See the examples of correct verifications:", + " verify(mock).someMethod();", + " verify(mock, times(10)).someMethod();", + " verify(mock, atLeastOnce()).someMethod();"); } - @Test(expected = NotAMockException.class) + @Test public void should_validate_mock_when_verifying_no_more_interactions() { - then("notMock").should(); + assertThatThrownBy( + () -> { + then("notMock").shouldHaveNoMoreInteractions(); + }) + .isInstanceOf(NotAMockException.class) + .hasMessageContainingAll( + "Argument(s) passed is not a mock!", + "Examples of correct verifications:", + " verifyNoMoreInteractions(mockOne, mockTwo);", + " verifyNoInteractions(mockOne, mockTwo);"); } - @Test(expected = WantedButNotInvoked.class) + @Test public void should_fail_for_expected_behavior_that_did_not_happen() { - then(mock).should().booleanObjectReturningMethod(); + assertThatThrownBy( + () -> { + then(mock).should().booleanObjectReturningMethod(); + }) + .isInstanceOf(WantedButNotInvoked.class) + .hasMessageContainingAll( + "Wanted but not invoked:", "mock.booleanObjectReturningMethod();"); } @Test @@ -305,9 +348,17 @@ public void should_fail_for_interactions_that_were_in_wrong_order() { } } - @Test(expected = WantedButNotInvoked.class) + @Test public void should_fail_when_checking_order_of_interactions_that_did_not_happen() { - then(mock).should(inOrder(mock)).booleanObjectReturningMethod(); + assertThatThrownBy( + () -> { + then(mock).should(inOrder(mock)).booleanObjectReturningMethod(); + }) + .isInstanceOf(WantedButNotInvoked.class) + .hasMessageContainingAll( + "Wanted but not invoked:", + "mock.booleanObjectReturningMethod();", + "Actually, there were zero interactions with this mock."); } @Test diff --git a/src/test/java/org/mockitousage/junitrule/LenientJUnitRuleTest.java b/src/test/java/org/mockitousage/junitrule/LenientJUnitRuleTest.java index c72e0ce3a0..617090a750 100644 --- a/src/test/java/org/mockitousage/junitrule/LenientJUnitRuleTest.java +++ b/src/test/java/org/mockitousage/junitrule/LenientJUnitRuleTest.java @@ -18,31 +18,27 @@ public class LenientJUnitRuleTest { private MockitoLogger explosiveLogger = - new MockitoLogger() { - public void log(Object what) { - throw new RuntimeException( - "Silent rule should not write anything to the logger"); - } + what -> { + throw new RuntimeException("Silent rule should not write anything to the logger"); }; @Mock private IMethods mock; @Rule public MockitoRule mockitoRule = new JUnitRule(explosiveLogger, Strictness.LENIENT); @Test - public void no_warning_for_unused_stubbing() throws Exception { + public void no_warning_for_unused_stubbing() { when(mock.simpleMethod(1)).thenReturn("1"); } @Test - public void no_warning_for_stubbing_arg_mismatch() throws Exception { + public void no_warning_for_stubbing_arg_mismatch() { when(mock.simpleMethod(1)).thenReturn("1"); mock.simpleMethod(2); } - @Test(expected = IllegalStateException.class) - public void no_warning_for_stubbing_arg_mismatch_on_failure() throws Exception { + @Test + public void no_warning_for_stubbing_arg_mismatch_on_failure() { when(mock.simpleMethod(1)).thenReturn("1"); mock.simpleMethod(2); - throw new IllegalStateException("hey!"); } } diff --git a/src/test/java/org/mockitousage/junitrule/VerificationCollectorImplTest.java b/src/test/java/org/mockitousage/junitrule/VerificationCollectorImplTest.java index 1500bcf39e..271c2135de 100644 --- a/src/test/java/org/mockitousage/junitrule/VerificationCollectorImplTest.java +++ b/src/test/java/org/mockitousage/junitrule/VerificationCollectorImplTest.java @@ -5,14 +5,18 @@ package org.mockitousage.junitrule; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.longThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.shortThat; +import static org.mockito.Mockito.verify; import org.junit.Rule; import org.junit.Test; import org.junit.runner.JUnitCore; import org.junit.runner.Result; -import org.mockito.ArgumentMatcher; import org.mockito.exceptions.base.MockitoAssertionError; import org.mockito.junit.MockitoJUnit; import org.mockito.junit.VerificationCollector; @@ -31,14 +35,23 @@ public void should_not_throw_any_exceptions_when_verifications_are_successful() collector.collectAndReport(); } - @Test(expected = MockitoAssertionError.class) + @Test public void should_collect_verification_failures() { VerificationCollector collector = MockitoJUnit.collector().assertLazily(); IMethods methods = mock(IMethods.class); verify(methods).simpleMethod(); - collector.collectAndReport(); + assertThatThrownBy( + () -> { + collector.collectAndReport(); + }) + .isInstanceOf(MockitoAssertionError.class) + .hasMessageContainingAll( + "There were multiple verification failures:", + "1. Wanted but not invoked:", + "iMethods.simpleMethod();", + "Actually, there were zero interactions with this mock."); } @Test @@ -78,21 +91,10 @@ public void should_collect_matching_error_from_non_matching_arguments() { verify(methods) .longArg( longThat( - new ArgumentMatcher() { - @Override - public boolean matches(Long argument) { - throw new AssertionError("custom error message"); - } - })); - verify(methods) - .forShort( - shortThat( - new ArgumentMatcher() { - @Override - public boolean matches(Short argument) { - return false; - } + argument -> { + throw new AssertionError("custom error message"); })); + verify(methods).forShort(shortThat(argument -> false)); try { collector.collectAndReport(); diff --git a/src/test/java/org/mockitousage/matchers/MatchersTest.java b/src/test/java/org/mockitousage/matchers/MatchersTest.java index c266862977..777c49a063 100644 --- a/src/test/java/org/mockitousage/matchers/MatchersTest.java +++ b/src/test/java/org/mockitousage/matchers/MatchersTest.java @@ -5,6 +5,7 @@ package org.mockitousage.matchers; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.fail; @@ -19,8 +20,8 @@ import static org.mockito.AdditionalMatchers.lt; import static org.mockito.AdditionalMatchers.not; import static org.mockito.AdditionalMatchers.or; -import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.ArgumentMatchers.nullable; import static org.mockito.Mockito.any; import static org.mockito.Mockito.anyBoolean; import static org.mockito.Mockito.anyByte; @@ -333,7 +334,7 @@ public void should_use_smart_equals_for_primitive_arrays() throws Exception { } @SuppressWarnings("ReturnValueIgnored") - @Test(expected = ArgumentsAreDifferent.class) + @Test public void array_equals_should_throw_ArgumentsAreDifferentException_for_non_matching_arguments() { List list = Mockito.mock(List.class); @@ -341,7 +342,16 @@ public void should_use_smart_equals_for_primitive_arrays() throws Exception { list.add("test"); // testing fix for issue 20 list.contains(new Object[] {"1"}); - Mockito.verify(list).contains(new Object[] {"1", "2", "3"}); + assertThatThrownBy( + () -> { + Mockito.verify(list).contains(new Object[] {"1", "2", "3"}); + }) + .isInstanceOf(ArgumentsAreDifferent.class) + .hasMessageContainingAll( + "Argument(s) are different! Wanted:", + "list.contains([\"1\", \"2\", \"3\"]);", + "Actual invocations have different arguments:", + "list.add(\"test\");"); } @Test diff --git a/src/test/java/org/mockitousage/matchers/ReflectionMatchersTest.java b/src/test/java/org/mockitousage/matchers/ReflectionMatchersTest.java index eac883ca0e..5afd360c15 100644 --- a/src/test/java/org/mockitousage/matchers/ReflectionMatchersTest.java +++ b/src/test/java/org/mockitousage/matchers/ReflectionMatchersTest.java @@ -4,6 +4,7 @@ */ package org.mockitousage.matchers; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.refEq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; @@ -61,28 +62,72 @@ public void shouldMatchWhenFieldValuesEqual() throws Exception { verify(mock).run(refEq(wanted)); } - @Test(expected = ArgumentsAreDifferent.class) + @Test public void shouldNotMatchWhenFieldValuesDiffer() throws Exception { Child wanted = new Child(1, "foo", 2, "bar XXX"); - verify(mock).run(refEq(wanted)); + assertThatThrownBy( + () -> { + verify(mock).run(refEq(wanted)); + }) + .isInstanceOf(ArgumentsAreDifferent.class) + .hasMessageContainingAll( + "Argument(s) are different! Wanted:", + "mockMe.run(", + " refEq(org.mockitousage.matchers.ReflectionMatchersTest", + "Actual invocations have different arguments:", + "mockMe.run(", + " org.mockitousage.matchers.ReflectionMatchersTest"); } - @Test(expected = ArgumentsAreDifferent.class) + @Test public void shouldNotMatchAgain() throws Exception { Child wanted = new Child(1, "foo", 999, "bar"); - verify(mock).run(refEq(wanted)); + assertThatThrownBy( + () -> { + verify(mock).run(refEq(wanted)); + }) + .isInstanceOf(ArgumentsAreDifferent.class) + .hasMessageContainingAll( + "Argument(s) are different! Wanted:", + "mockMe.run(", + " refEq(org.mockitousage.matchers.ReflectionMatchersTest", + "Actual invocations have different arguments:", + "mockMe.run(", + " org.mockitousage.matchers.ReflectionMatchersTest"); } - @Test(expected = ArgumentsAreDifferent.class) + @Test public void shouldNotMatchYetAgain() throws Exception { Child wanted = new Child(1, "XXXXX", 2, "bar"); - verify(mock).run(refEq(wanted)); + assertThatThrownBy( + () -> { + verify(mock).run(refEq(wanted)); + }) + .isInstanceOf(ArgumentsAreDifferent.class) + .hasMessageContainingAll( + "Argument(s) are different! Wanted:", + "mockMe.run(", + " refEq(org.mockitousage.matchers.ReflectionMatchersTest", + "Actual invocations have different arguments:", + "mockMe.run(", + " org.mockitousage.matchers.ReflectionMatchersTest"); } - @Test(expected = ArgumentsAreDifferent.class) + @Test public void shouldNotMatch() throws Exception { Child wanted = new Child(234234, "foo", 2, "bar"); - verify(mock).run(refEq(wanted)); + assertThatThrownBy( + () -> { + verify(mock).run(refEq(wanted)); + }) + .isInstanceOf(ArgumentsAreDifferent.class) + .hasMessageContainingAll( + "Argument(s) are different! Wanted:", + "mockMe.run(", + " refEq(org.mockitousage.matchers.ReflectionMatchersTest", + "Actual invocations have different arguments:", + "mockMe.run(", + " org.mockitousage.matchers.ReflectionMatchersTest"); } @Test @@ -98,9 +143,20 @@ public void shouldMatchWhenFieldValuesEqualWithTwoFieldsExcluded() throws Except verify(mock).run(refEq(wanted, "parentField", "childFieldTwo")); } - @Test(expected = ArgumentsAreDifferent.class) + @Test public void shouldNotMatchWithFieldsExclusion() throws Exception { Child wanted = new Child(234234, "foo", 2, "excluded"); - verify(mock).run(refEq(wanted, "childFieldTwo")); + assertThatThrownBy( + () -> { + verify(mock).run(refEq(wanted, "childFieldTwo")); + }) + .isInstanceOf(ArgumentsAreDifferent.class) + .hasMessageContainingAll( + "Argument(s) are different! Wanted:", + "mockMe.run(", + " refEq(org.mockitousage.matchers.ReflectionMatchersTest", + "Actual invocations have different arguments:", + "mockMe.run(", + " org.mockitousage.matchers.ReflectionMatchersTest"); } } diff --git a/src/test/java/org/mockitousage/matchers/VarargsTest.java b/src/test/java/org/mockitousage/matchers/VarargsTest.java index dbcee31dad..dfb726942b 100644 --- a/src/test/java/org/mockitousage/matchers/VarargsTest.java +++ b/src/test/java/org/mockitousage/matchers/VarargsTest.java @@ -4,6 +4,7 @@ */ package org.mockitousage.matchers; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; @@ -19,7 +20,6 @@ import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.ArgumentCaptor; import org.mockito.ArgumentMatchers; import org.mockito.Captor; @@ -32,7 +32,6 @@ public class VarargsTest { @Rule public MockitoRule mockitoRule = MockitoJUnit.rule(); - @Rule public ExpectedException exception = ExpectedException.none(); @Captor private ArgumentCaptor captor; @Mock private IMethods mock; @@ -104,9 +103,11 @@ public void shouldMatchVarArgs_nullArrayArg() { public void shouldnotMatchVarArgs_twoArgsOneMatcher() { mock.varargs("1", "1"); - exception.expectMessage("Argument(s) are different"); - - verify(mock).varargs(eq("1")); + assertThatThrownBy( + () -> { + verify(mock).varargs(eq("1")); + }) + .hasMessageContaining("Argument(s) are different"); } @Test @@ -141,9 +142,11 @@ public void shouldMatchVarArgs_twoArgsTwoAnyMatcher() { public void shouldMatchVarArgs_twoArgsThreeAnyMatcher() { mock.varargs(1, 2); - exception.expectMessage("Argument(s) are different"); - - verify(mock).varargs(any(), any(), any()); // any() -> VarargMatcher + assertThatThrownBy( + () -> { + verify(mock).varargs(any(), any(), any()); // any() -> VarargMatcher + }) + .hasMessageContaining("Argument(s) are different"); } @Test @@ -261,9 +264,11 @@ public void shouldCaptureVarArgs_oneNullArgument2() { public void shouldNotCaptureVarArgs_3args2captures() { mock.varargs("1", "2", "3"); - exception.expect(ArgumentsAreDifferent.class); - - verify(mock).varargs(captor.capture(), captor.capture()); + assertThatThrownBy( + () -> { + verify(mock).varargs(captor.capture(), captor.capture()); + }) + .isInstanceOf(ArgumentsAreDifferent.class); } @Test @@ -292,9 +297,11 @@ public void shouldNotCaptureVarArgs_3argsCaptorMatcherMix() { public void shouldNotCaptureVarArgs_1args2captures() { mock.varargs("1"); - exception.expect(ArgumentsAreDifferent.class); - - verify(mock).varargs(captor.capture(), captor.capture()); + assertThatThrownBy( + () -> { + verify(mock).varargs(captor.capture(), captor.capture()); + }) + .isInstanceOf(ArgumentsAreDifferent.class); } /** @@ -321,9 +328,11 @@ public void shouldCaptureVarArgsAsArray() { public void shouldNotMatchRegualrAndVaraArgs() { mock.varargsString(1, "a", "b"); - exception.expect(ArgumentsAreDifferent.class); - - verify(mock).varargsString(1); + assertThatThrownBy( + () -> { + verify(mock).varargsString(1); + }) + .isInstanceOf(ArgumentsAreDifferent.class); } @Test diff --git a/src/test/java/org/mockitousage/misuse/DescriptiveMessagesOnMisuseTest.java b/src/test/java/org/mockitousage/misuse/DescriptiveMessagesOnMisuseTest.java index a61837462a..3cd9485b35 100644 --- a/src/test/java/org/mockitousage/misuse/DescriptiveMessagesOnMisuseTest.java +++ b/src/test/java/org/mockitousage/misuse/DescriptiveMessagesOnMisuseTest.java @@ -4,7 +4,11 @@ */ package org.mockitousage.misuse; -import static org.mockito.Mockito.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; import org.junit.Test; import org.mockito.Mock; @@ -58,42 +62,110 @@ public void tryDescriptiveMessagesOnMisuse() { } @SuppressWarnings({"MockitoUsage", "CheckReturnValue"}) - @Test(expected = NotAMockException.class) + @Test public void shouldScreamWhenWholeMethodPassedToVerify() { - verify(mock.booleanReturningMethod()); + assertThatThrownBy( + () -> { + verify(mock.booleanReturningMethod()); + }) + .isInstanceOf(NotAMockException.class) + .hasMessageContainingAll( + "Argument passed to verify() is of type Boolean and is not a mock!", + "Make sure you place the parenthesis correctly!", + "See the examples of correct verifications:", + " verify(mock).someMethod();", + " verify(mock, times(10)).someMethod();", + " verify(mock, atLeastOnce()).someMethod();"); } - @Test(expected = NotAMockException.class) + @Test public void shouldScreamWhenWholeMethodPassedToVerifyNoMoreInteractions() { - verifyNoMoreInteractions(mock.byteReturningMethod()); + assertThatThrownBy( + () -> { + verifyNoMoreInteractions(mock.byteReturningMethod()); + }) + .isInstanceOf(NotAMockException.class) + .hasMessageContainingAll( + "Argument(s) passed is not a mock!", + "Examples of correct verifications:", + " verifyNoMoreInteractions(mockOne, mockTwo);", + " verifyNoInteractions(mockOne, mockTwo);"); } @SuppressWarnings({"CheckReturnValue", "MockitoUsage"}) - @Test(expected = NotAMockException.class) + @Test public void shouldScreamWhenInOrderCreatedWithDodgyMock() { - inOrder("not a mock"); + assertThatThrownBy( + () -> { + inOrder("not a mock"); + }) + .isInstanceOf(NotAMockException.class) + .hasMessageContainingAll( + "Argument(s) passed is not a mock!", + "Pass mocks that require verification in order.", + "For example:", + " InOrder inOrder = inOrder(mockOne, mockTwo);"); } @SuppressWarnings({"CheckReturnValue", "MockitoUsage"}) - @Test(expected = NullInsteadOfMockException.class) + @Test public void shouldScreamWhenInOrderCreatedWithNulls() { - inOrder(mock, null); + assertThatThrownBy( + () -> { + inOrder(mock, null); + }) + .isInstanceOf(NullInsteadOfMockException.class) + .hasMessageContainingAll( + "Argument(s) passed is null!", + "Pass mocks that require verification in order.", + "For example:", + " InOrder inOrder = inOrder(mockOne, mockTwo);"); } @SuppressWarnings({"MockitoUsage", "CheckReturnValue"}) - @Test(expected = NullInsteadOfMockException.class) + @Test public void shouldScreamNullPassedToVerify() { - verify(null); + assertThatThrownBy( + () -> { + verify(null); + }) + .isInstanceOf(NullInsteadOfMockException.class) + .hasMessageContainingAll( + "Argument passed to verify() should be a mock but is null!", + "Examples of correct verifications:", + " verify(mock).someMethod();", + " verify(mock, times(10)).someMethod();", + " verify(mock, atLeastOnce()).someMethod();", + " not: verify(mock.someMethod());", + "Also, if you use @Mock annotation don't miss openMocks()"); } - @Test(expected = NullInsteadOfMockException.class) + @Test public void shouldScreamWhenNotMockPassedToVerifyNoMoreInteractions() { - verifyNoMoreInteractions(null, "blah"); + assertThatThrownBy( + () -> { + verifyNoMoreInteractions(null, "blah"); + }) + .isInstanceOf(NullInsteadOfMockException.class) + .hasMessageContainingAll( + "Argument(s) passed is null!", + "Examples of correct verifications:", + " verifyNoMoreInteractions(mockOne, mockTwo);", + " verifyNoInteractions(mockOne, mockTwo);"); } @SuppressWarnings("all") - @Test(expected = MockitoException.class) + @Test public void shouldScreamWhenNullPassedToVerifyNoMoreInteractions() { - verifyNoMoreInteractions((Object[]) null); + assertThatThrownBy( + () -> { + verifyNoMoreInteractions((Object[]) null); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "Method requires argument(s)!", + "Pass mocks that should be verified, e.g:", + " verifyNoMoreInteractions(mockOne, mockTwo);", + " verifyNoInteractions(mockOne, mockTwo);"); } } diff --git a/src/test/java/org/mockitousage/misuse/InvalidUsageTest.java b/src/test/java/org/mockitousage/misuse/InvalidUsageTest.java index ce418bfedb..35c135a62e 100644 --- a/src/test/java/org/mockitousage/misuse/InvalidUsageTest.java +++ b/src/test/java/org/mockitousage/misuse/InvalidUsageTest.java @@ -4,8 +4,12 @@ */ package org.mockitousage.misuse; -import static org.junit.Assume.assumeFalse; -import static org.mockito.Mockito.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; import org.junit.After; import org.junit.Test; @@ -26,69 +30,154 @@ public void resetState() { super.resetState(); } - @Test(expected = MockitoException.class) + @Test public void shouldRequireArgumentsWhenVerifyingNoMoreInteractions() { - verifyNoMoreInteractions(); + assertThatThrownBy( + () -> { + verifyNoMoreInteractions(); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "Method requires argument(s)!", + "Pass mocks that should be verified, e.g:", + " verifyNoMoreInteractions(mockOne, mockTwo);", + " verifyNoInteractions(mockOne, mockTwo);"); } - @Test(expected = MockitoException.class) + @Test public void shouldRequireArgumentsWhenVerifyingNoInteractions() { - verifyNoInteractions(); + assertThatThrownBy( + () -> { + verifyNoInteractions(); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "Method requires argument(s)!", + "Pass mocks that should be verified, e.g:", + " verifyNoMoreInteractions(mockOne, mockTwo);", + " verifyNoInteractions(mockOne, mockTwo);"); } @SuppressWarnings({"CheckReturnValue", "MockitoUsage"}) - @Test(expected = MockitoException.class) + @Test public void shouldNotCreateInOrderObjectWithoutMocks() { - inOrder(); + assertThatThrownBy( + () -> { + inOrder(); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "Method requires argument(s)!", + "Pass mocks that require verification in order.", + "For example:", + " InOrder inOrder = inOrder(mockOne, mockTwo);"); } - @Test(expected = MockitoException.class) - public void shouldNotAllowVerifyingInOrderUnfamilarMocks() { + @Test + public void shouldNotAllowVerifyingInOrderUnfamiliarMocks() { InOrder inOrder = inOrder(mock); - inOrder.verify(mockTwo).simpleMethod(); + assertThatThrownBy( + () -> { + inOrder.verify(mockTwo).simpleMethod(); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "InOrder can only verify mocks that were passed in during creation of InOrder.", + "For example:", + " InOrder inOrder = inOrder(mockOne);", + " inOrder.verify(mockOne).doStuff();"); } - @Test(expected = MissingMethodInvocationException.class) + @Test public void shouldReportMissingMethodInvocationWhenStubbing() { when(mock.simpleMethod()) .thenReturn("this stubbing is required to make sure Stubbable is pulled"); - when("".toString()).thenReturn("x"); + assertThatThrownBy( + () -> { + when("".toString()).thenReturn("x"); + }) + .isInstanceOf(MissingMethodInvocationException.class) + .hasMessageContainingAll( + "when() requires an argument which has to be 'a method call on a mock'.", + "For example:", + " when(mock.getArticles()).thenReturn(articles);", + "Also, this error might show up because:", + "1. you stub either of: final/private/equals()/hashCode() methods.", + " Those methods *cannot* be stubbed/verified.", + " Mocking methods declared on non-public parent classes is not supported.", + "2. inside when() you don't call method on mock but on some other object."); } - @Test(expected = MockitoException.class) - public void shouldNotAllowSettingInvalidCheckedException() throws Exception { - when(mock.simpleMethod()).thenThrow(new Exception()); + @Test + public void shouldNotAllowSettingInvalidCheckedException() { + assertThatThrownBy( + () -> { + when(mock.simpleMethod()).thenThrow(new Exception()); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "Checked exception is invalid for this method!", + "Invalid: java.lang.Exception"); } - @Test(expected = MockitoException.class) - public void shouldNotAllowSettingNullThrowable() throws Exception { - when(mock.simpleMethod()).thenThrow(new Throwable[] {null}); + @Test + public void shouldNotAllowSettingNullThrowable() { + assertThatThrownBy( + () -> { + when(mock.simpleMethod()).thenThrow(new Throwable[] {null}); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("Cannot stub with null throwable!"); } @SuppressWarnings("all") - @Test(expected = MockitoException.class) + @Test public void shouldNotAllowSettingNullThrowableVararg() throws Exception { - when(mock.simpleMethod()).thenThrow((Throwable) null); + assertThatThrownBy( + () -> { + when(mock.simpleMethod()).thenThrow((Throwable) null); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("Cannot stub with null throwable!"); } - @Test(expected = MockitoException.class) - public void shouldNotAllowSettingNullConsecutiveThrowable() throws Exception { - when(mock.simpleMethod()).thenThrow(new RuntimeException(), null); + @Test + public void shouldNotAllowSettingNullConsecutiveThrowable() { + assertThatThrownBy( + () -> { + when(mock.simpleMethod()).thenThrow(new RuntimeException(), null); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("Cannot stub with null throwable!"); } final class FinalClass {} - @Test(expected = MockitoException.class) - public void shouldNotAllowMockingFinalClassesIfDisabled() throws Exception { - assumeFalse( - "Inlining mock allows mocking final classes", - mock(FinalClass.class).getClass() == FinalClass.class); + @Test + public void shouldNotAllowMockingFinalClassesIfDisabled() { + assertThatThrownBy( + () -> { + mock(FinalClass.class); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "Cannot mock/spy class org.mockitousage.misuse.InvalidUsageTest$FinalClass", + "Mockito cannot mock/spy because :", + " - final class"); } @SuppressWarnings({"CheckReturnValue", "MockitoUsage"}) - @Test(expected = MockitoException.class) - public void shouldNotAllowMockingPrimitives() throws Exception { - mock(Integer.TYPE); + @Test + public void shouldNotAllowMockingPrimitives() { + assertThatThrownBy( + () -> { + mock(Integer.TYPE); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "Cannot mock/spy int", + "Mockito cannot mock/spy because :", + " - primitive type"); } interface ObjectLikeInterface { @@ -100,7 +189,7 @@ interface ObjectLikeInterface { } @Test - public void shouldNotMockObjectMethodsOnInterfaceVerifyNoInteractions() throws Exception { + public void shouldNotMockObjectMethodsOnInterfaceVerifyNoInteractions() { ObjectLikeInterface inter = mock(ObjectLikeInterface.class); Object ignored = inter.equals(null); @@ -111,7 +200,7 @@ public void shouldNotMockObjectMethodsOnInterfaceVerifyNoInteractions() throws E } @Test - public void shouldNotMockObjectMethodsOnClassVerifyNoInteractions() throws Exception { + public void shouldNotMockObjectMethodsOnClassVerifyNoInteractions() { Object clazz = mock(ObjectLikeInterface.class); Object ignored = clazz.equals(null); diff --git a/src/test/java/org/mockitousage/stubbing/StubbingConsecutiveAnswersTest.java b/src/test/java/org/mockitousage/stubbing/StubbingConsecutiveAnswersTest.java index 6098805e1c..0d64e2b130 100644 --- a/src/test/java/org/mockitousage/stubbing/StubbingConsecutiveAnswersTest.java +++ b/src/test/java/org/mockitousage/stubbing/StubbingConsecutiveAnswersTest.java @@ -4,8 +4,13 @@ */ package org.mockitousage.stubbing; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.when; import org.junit.Test; import org.mockito.Mock; @@ -18,7 +23,7 @@ public class StubbingConsecutiveAnswersTest extends TestBase { @Mock private IMethods mock; @Test - public void should_return_consecutive_values() throws Exception { + public void should_return_consecutive_values() { when(mock.simpleMethod()).thenReturn("one").thenReturn("two").thenReturn("three"); assertEquals("one", mock.simpleMethod()); @@ -29,7 +34,7 @@ public void should_return_consecutive_values() throws Exception { } @Test - public void should_return_consecutive_values_for_two_nulls() throws Exception { + public void should_return_consecutive_values_for_two_nulls() { when(mock.simpleMethod()).thenReturn(null, (String[]) null); assertNull(mock.simpleMethod()); @@ -37,7 +42,7 @@ public void should_return_consecutive_values_for_two_nulls() throws Exception { } @Test - public void should_return_consecutive_values_first_var_arg_null() throws Exception { + public void should_return_consecutive_values_first_var_arg_null() { when(mock.simpleMethod()).thenReturn("one", (String) null); assertEquals("one", mock.simpleMethod()); @@ -46,7 +51,7 @@ public void should_return_consecutive_values_first_var_arg_null() throws Excepti } @Test - public void should_return_consecutive_values_var_arg_null() throws Exception { + public void should_return_consecutive_values_var_arg_null() { when(mock.simpleMethod()).thenReturn("one", (String[]) null); assertEquals("one", mock.simpleMethod()); @@ -55,7 +60,7 @@ public void should_return_consecutive_values_var_arg_null() throws Exception { } @Test - public void should_return_consecutive_values_var_args_contain_null() throws Exception { + public void should_return_consecutive_values_var_args_contain_null() { when(mock.simpleMethod()).thenReturn("one", "two", null); assertEquals("one", mock.simpleMethod()); @@ -65,8 +70,7 @@ public void should_return_consecutive_values_var_args_contain_null() throws Exce } @Test - public void should_return_consecutive_values_set_by_shorten_then_return_method() - throws Exception { + public void should_return_consecutive_values_set_by_shorten_then_return_method() { when(mock.simpleMethod()).thenReturn("one", "two", "three"); assertEquals("one", mock.simpleMethod()); @@ -108,7 +112,7 @@ public void should_return_consecutive_values_set_by_shorten_then_return_method() } @Test - public void should_throw_consecutively() throws Exception { + public void should_throw_consecutively() { when(mock.simpleMethod()) .thenThrow(new RuntimeException()) .thenThrow(new IllegalArgumentException()) @@ -140,7 +144,7 @@ public void should_throw_consecutively() throws Exception { } @Test - public void should_throw_consecutively_set_by_shorten_then_throw_method() throws Exception { + public void should_throw_consecutively_set_by_shorten_then_throw_method() { when(mock.simpleMethod()) .thenThrow( new RuntimeException(), @@ -173,7 +177,7 @@ public void should_throw_consecutively_set_by_shorten_then_throw_method() throws } @Test - public void should_throw_classes() throws Exception { + public void should_throw_classes() { // Unavoidable JDK7+ 'unchecked generic array creation' warning when(mock.simpleMethod()).thenThrow(IllegalArgumentException.class); @@ -192,8 +196,7 @@ public void should_throw_classes() throws Exception { @Test @SuppressWarnings("unchecked") - public void should_throw_consecutively_classes_set_by_shorten_then_throw_method() - throws Exception { + public void should_throw_consecutively_classes_set_by_shorten_then_throw_method() { // Unavoidable JDK7+ 'unchecked generic array creation' warning when(mock.simpleMethod()) .thenThrow( @@ -227,7 +230,7 @@ public void should_throw_consecutively_classes_set_by_shorten_then_throw_method( } @Test - public void should_mix_consecutive_returns_with_exceptions() throws Exception { + public void should_mix_consecutive_returns_with_exceptions() { when(mock.simpleMethod()) .thenThrow(new IllegalArgumentException()) .thenReturn("one") @@ -252,13 +255,20 @@ public void should_mix_consecutive_returns_with_exceptions() throws Exception { assertEquals(null, mock.simpleMethod()); } - @Test(expected = MockitoException.class) - public void should_validate_consecutive_exception() throws Exception { - when(mock.simpleMethod()).thenReturn("one").thenThrow(new Exception()); + @Test + public void should_validate_consecutive_exception() { + assertThatThrownBy( + () -> { + when(mock.simpleMethod()).thenReturn("one").thenThrow(new Exception()); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "Checked exception is invalid for this method!", + "Invalid: java.lang.Exception"); } @Test - public void should_stub_void_method_and_continue_throwing() throws Exception { + public void should_stub_void_method_and_continue_throwing() { doThrow(new IllegalArgumentException()) .doNothing() .doThrow(new NullPointerException()) @@ -287,7 +297,7 @@ public void should_stub_void_method_and_continue_throwing() throws Exception { } @Test - public void should_stub_void_method() throws Exception { + public void should_stub_void_method() { doNothing().doThrow(new NullPointerException()).doNothing().when(mock).voidMethod(); mock.voidMethod(); @@ -302,8 +312,15 @@ public void should_stub_void_method() throws Exception { mock.voidMethod(); } - @Test(expected = MockitoException.class) - public void should_validate_consecutive_exception_for_void_method() throws Exception { - doNothing().doThrow(new Exception()).when(mock).voidMethod(); + @Test + public void should_validate_consecutive_exception_for_void_method() { + assertThatThrownBy( + () -> { + doNothing().doThrow(new Exception()).when(mock).voidMethod(); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "Checked exception is invalid for this method!", + "Invalid: java.lang.Exception"); } } diff --git a/src/test/java/org/mockitousage/stubbing/StubbingUsingDoReturnTest.java b/src/test/java/org/mockitousage/stubbing/StubbingUsingDoReturnTest.java index e9776f4f45..53d902945d 100644 --- a/src/test/java/org/mockitousage/stubbing/StubbingUsingDoReturnTest.java +++ b/src/test/java/org/mockitousage/stubbing/StubbingUsingDoReturnTest.java @@ -5,18 +5,26 @@ package org.mockitousage.stubbing; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.anyInt; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; import java.io.IOException; -import org.assertj.core.api.Assertions; import org.junit.After; import org.junit.Test; import org.mockito.Mock; import org.mockito.exceptions.base.MockitoException; import org.mockito.exceptions.verification.NoInteractionsWanted; -import org.mockito.invocation.InvocationOnMock; import org.mockito.stubbing.Answer; import org.mockitousage.IMethods; import org.mockitousage.MethodsImpl; @@ -33,27 +41,27 @@ public void reset_state() { } @Test - public void should_stub() throws Exception { + public void should_stub() { doReturn("foo").when(mock).simpleMethod(); doReturn("bar").when(mock).simpleMethod(); - Assertions.assertThat(mock.simpleMethod()).isEqualTo("bar"); + assertThat(mock.simpleMethod()).isEqualTo("bar"); } @Test - public void should_stub_with_args() throws Exception { + public void should_stub_with_args() { doReturn("foo").when(mock).simpleMethod("foo"); doReturn("bar").when(mock).simpleMethod(eq("one"), anyInt()); - Assertions.assertThat(mock.simpleMethod("foo")).isEqualTo("foo"); - Assertions.assertThat(mock.simpleMethod("one", 234)).isEqualTo("bar"); - Assertions.assertThat(mock.simpleMethod("xxx", 234)).isEqualTo(null); + assertThat(mock.simpleMethod("foo")).isEqualTo("foo"); + assertThat(mock.simpleMethod("one", 234)).isEqualTo("bar"); + assertThat(mock.simpleMethod("xxx", 234)).isNull(); } class FooRuntimeException extends RuntimeException {} @Test - public void should_stub_with_throwable() throws Exception { + public void should_stub_with_throwable() { doThrow(new FooRuntimeException()).when(mock).voidMethod(); try { mock.voidMethod(); @@ -76,7 +84,7 @@ public void should_allow_setting_valid_checked_exception() throws Exception { class FooCheckedException extends Exception {} @Test - public void should_detect_invalid_checked_exception() throws Exception { + public void should_detect_invalid_checked_exception() { try { doThrow(new FooCheckedException()).when(mock).throwsIOException(0); fail(); @@ -86,7 +94,7 @@ public void should_detect_invalid_checked_exception() throws Exception { } @Test - public void should_scream_when_return_set_for_void() throws Exception { + public void should_scream_when_return_set_for_void() { try { doReturn("foo").when(mock).voidMethod(); fail(); @@ -96,7 +104,7 @@ public void should_scream_when_return_set_for_void() throws Exception { } @Test - public void should_scream_when_not_a_mock_passed() throws Exception { + public void should_scream_when_not_a_mock_passed() { try { doReturn("foo").when("foo").toString(); fail(); @@ -106,7 +114,7 @@ public void should_scream_when_not_a_mock_passed() throws Exception { } @Test - public void should_scream_when_null_passed() throws Exception { + public void should_scream_when_null_passed() { try { doReturn("foo").when((Object) null).toString(); fail(); @@ -119,15 +127,15 @@ public void should_scream_when_null_passed() throws Exception { public void should_allow_chained_stubbing() { doReturn("foo").doThrow(new RuntimeException()).doReturn("bar").when(mock).simpleMethod(); - Assertions.assertThat(mock.simpleMethod()).isEqualTo("foo"); + assertThat(mock.simpleMethod()).isEqualTo("foo"); try { mock.simpleMethod(); fail(); } catch (RuntimeException expected) { } - Assertions.assertThat(mock.simpleMethod()).isEqualTo("bar"); - Assertions.assertThat(mock.simpleMethod()).isEqualTo("bar"); + assertThat(mock.simpleMethod()).isEqualTo("bar"); + assertThat(mock.simpleMethod()).isEqualTo("bar"); } @Test @@ -138,35 +146,39 @@ public void should_allow_consecutive_return_values() { .when(mock) .objectReturningMethodNoArgs(); - Assertions.assertThat(mock.objectReturningMethodNoArgs()).isEqualTo("foo"); - Assertions.assertThat(mock.objectReturningMethodNoArgs()).isEqualTo("bar"); + assertThat(mock.objectReturningMethodNoArgs()).isEqualTo("foo"); + assertThat(mock.objectReturningMethodNoArgs()).isEqualTo("bar"); try { mock.objectReturningMethodNoArgs(); fail("exception not raised"); } catch (RuntimeException expected) { } - Assertions.assertThat(mock.objectReturningMethodNoArgs()).isEqualTo(430L); - Assertions.assertThat(mock.objectReturningMethodNoArgs()).isEqualTo(new byte[0]); - Assertions.assertThat(mock.objectReturningMethodNoArgs()).isEqualTo("qix"); - Assertions.assertThat(mock.objectReturningMethodNoArgs()).isEqualTo("qix"); + assertThat(mock.objectReturningMethodNoArgs()).isEqualTo(430L); + assertThat(mock.objectReturningMethodNoArgs()).isEqualTo(new byte[0]); + assertThat(mock.objectReturningMethodNoArgs()).isEqualTo("qix"); + assertThat(mock.objectReturningMethodNoArgs()).isEqualTo("qix"); } @Test - public void should_allow_do_call_real_method_in_chained_stubbing() throws Exception { + public void should_allow_do_call_real_method_in_chained_stubbing() { MethodsImpl methods = mock(MethodsImpl.class); doReturn("A").doCallRealMethod().when(methods).simpleMethod(); - Assertions.assertThat(methods.simpleMethod()).isEqualTo("A"); - Assertions.assertThat(methods.simpleMethod()).isEqualTo(null); + assertThat(methods.simpleMethod()).isEqualTo("A"); + assertThat(methods.simpleMethod()).isNull(); } - @Test(expected = IllegalArgumentException.class) - public void should_allow_chained_stubbing_with_exception_class() throws Exception { + @Test + public void should_allow_chained_stubbing_with_exception_class() { doReturn("whatever").doThrow(IllegalArgumentException.class).when(mock).simpleMethod(); - Assertions.assertThat(mock.simpleMethod()).isEqualTo("whatever"); - mock.simpleMethod(); + assertThat(mock.simpleMethod()).isEqualTo("whatever"); + assertThatThrownBy( + () -> { + mock.simpleMethod(); + }) + .isInstanceOf(IllegalArgumentException.class); } @Test @@ -189,16 +201,9 @@ public void should_allow_chained_stubbing_on_void_methods() { @Test public void should_stub_with_generic_answer() { - doAnswer( - new Answer() { - public Object answer(InvocationOnMock invocation) throws Throwable { - return "foo"; - } - }) - .when(mock) - .simpleMethod(); + doAnswer((Answer) invocation -> "foo").when(mock).simpleMethod(); - Assertions.assertThat(mock.simpleMethod()).isEqualTo("foo"); + assertThat(mock.simpleMethod()).isEqualTo("foo"); } @Test @@ -212,7 +217,7 @@ public void should_not_allow_do_nothing_on_non_voids() { } @Test - public void should_stubbing_be_treated_as_interaction() throws Exception { + public void should_stubbing_be_treated_as_interaction() { doReturn("foo").when(mock).simpleMethod(); mock.simpleMethod(); try { @@ -223,7 +228,7 @@ public void should_stubbing_be_treated_as_interaction() throws Exception { } @Test - public void should_verify_stubbed_call() throws Exception { + public void should_verify_stubbed_call() { doReturn("foo").when(mock).simpleMethod(); mock.simpleMethod(); mock.simpleMethod(); @@ -233,13 +238,13 @@ public void should_verify_stubbed_call() throws Exception { } @Test - public void should_allow_stubbing_to_string() throws Exception { + public void should_allow_stubbing_to_string() { doReturn("test").when(mock).toString(); - Assertions.assertThat(mock.toString()).isEqualTo("test"); + assertThat(mock.toString()).isEqualTo("test"); } @Test - public void should_detect_invalid_return_type() throws Exception { + public void should_detect_invalid_return_type() { try { doReturn("foo").when(mock).booleanObjectReturningMethod(); fail(); @@ -253,7 +258,7 @@ public void should_detect_invalid_return_type() throws Exception { } @Test - public void should_detect_when_null_assigned_to_boolean() throws Exception { + public void should_detect_when_null_assigned_to_boolean() { try { doReturn(null).when(mock).intReturningMethod(); fail(); @@ -263,7 +268,7 @@ public void should_detect_when_null_assigned_to_boolean() throws Exception { } @Test - public void should_allow_stubbing_when_types_match_signature() throws Exception { + public void should_allow_stubbing_when_types_match_signature() { doReturn("foo").when(mock).objectReturningMethodNoArgs(); doReturn("foo").when(mock).simpleMethod(); doReturn(1).when(mock).intReturningMethod(); diff --git a/src/test/java/org/mockitousage/stubbing/StubbingWarningsTest.java b/src/test/java/org/mockitousage/stubbing/StubbingWarningsTest.java index b959e99d8b..c2564f70e9 100644 --- a/src/test/java/org/mockitousage/stubbing/StubbingWarningsTest.java +++ b/src/test/java/org/mockitousage/stubbing/StubbingWarningsTest.java @@ -5,7 +5,7 @@ package org.mockitousage.stubbing; import static java.util.Collections.singletonList; - +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; @@ -41,7 +41,7 @@ public void after() { } @Test - public void few_interactions() throws Throwable { + public void few_interactions() { // when mock.simpleMethod(100); mock.otherMethod(); @@ -52,7 +52,7 @@ public void few_interactions() throws Throwable { } @Test - public void stubbing_used() throws Throwable { + public void stubbing_used() { // when given(mock.simpleMethod(100)).willReturn("100"); mock.simpleMethod(100); @@ -63,7 +63,7 @@ public void stubbing_used() throws Throwable { } @Test - public void unused_stubbed_is_not_implicitly_verified() throws Throwable { + public void unused_stubbed_is_not_implicitly_verified() { // when given(mock.simpleMethod(100)).willReturn("100"); mock.simpleMethod(100); // <- stubbing is used @@ -75,7 +75,7 @@ public void unused_stubbed_is_not_implicitly_verified() throws Throwable { } @Test - public void stubbing_argument_mismatch() throws Throwable { + public void stubbing_argument_mismatch() { // when given(mock.simpleMethod(100)).willReturn("100"); mock.simpleMethod(200); @@ -96,7 +96,7 @@ public void stubbing_argument_mismatch() throws Throwable { } @Test - public void unused_stubbing() throws Throwable { + public void unused_stubbing() { // when given(mock.simpleMethod(100)).willReturn("100"); @@ -113,17 +113,29 @@ public void unused_stubbing() throws Throwable { } @SuppressWarnings({"MockitoUsage", "CheckReturnValue"}) - @Test(expected = MockitoException.class) - public void unfinished_verification_without_throwable() throws Throwable { + @Test + public void unfinished_verification_without_throwable() { // when verify(mock); - mockito.finishMocking(); + assertThatThrownBy( + () -> { + mockito.finishMocking(); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "Missing method call for verify(mock) here:", + "-> at", + "Example of correct verification:", + " verify(mock).doSomething()", + "Also, this error might show up because you verify either of: final/private/equals()/hashCode() methods.", + "Those methods *cannot* be stubbed/verified.", + "Mocking methods declared on non-public parent classes is not supported."); } @SuppressWarnings({"MockitoUsage", "CheckReturnValue"}) @Test - public void unfinished_verification_with_throwable() throws Throwable { + public void unfinished_verification_with_throwable() { // when verify(mock); diff --git a/src/test/java/org/mockitousage/stubbing/StubbingWithThrowablesTest.java b/src/test/java/org/mockitousage/stubbing/StubbingWithThrowablesTest.java index 625961c1a0..045a8b6599 100644 --- a/src/test/java/org/mockitousage/stubbing/StubbingWithThrowablesTest.java +++ b/src/test/java/org/mockitousage/stubbing/StubbingWithThrowablesTest.java @@ -4,7 +4,7 @@ */ package org.mockitousage.stubbing; -import static org.hamcrest.CoreMatchers.sameInstance; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertNull; @@ -24,11 +24,8 @@ import java.util.Map; import org.assertj.core.api.Assertions; -import org.assertj.core.api.ThrowableAssert; import org.junit.Before; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.exceptions.base.MockitoException; import org.mockito.exceptions.verification.NoInteractionsWanted; import org.mockito.exceptions.verification.WantedButNotInvoked; @@ -42,8 +39,6 @@ public class StubbingWithThrowablesTest extends TestBase { private Map mockTwo; - @Rule public ExpectedException exception = ExpectedException.none(); - @Before public void setup() { mock = mock(LinkedList.class); @@ -55,22 +50,18 @@ public void throws_same_exception_consecutively() { when(mock.add("")).thenThrow(new ExceptionOne()); // 1st invocation - Assertions.assertThatThrownBy( - new ThrowableAssert.ThrowingCallable() { - public void call() { - mock.add(""); - } + assertThatThrownBy( + () -> { + mock.add(""); }) .isInstanceOf(ExceptionOne.class); mock.add("1"); // 2nd invocation - Assertions.assertThatThrownBy( - new ThrowableAssert.ThrowingCallable() { - public void call() { - mock.add(""); - } + assertThatThrownBy( + () -> { + mock.add(""); }) .isInstanceOf(ExceptionOne.class); } @@ -80,22 +71,18 @@ public void throws_same_exception_consecutively_with_doThrow() { doThrow(new ExceptionOne()).when(mock).clear(); // 1st invocation - Assertions.assertThatThrownBy( - new ThrowableAssert.ThrowingCallable() { - public void call() { - mock.clear(); - } + assertThatThrownBy( + () -> { + mock.clear(); }) .isInstanceOf(ExceptionOne.class); mock.add("1"); // 2nd invocation - Assertions.assertThatThrownBy( - new ThrowableAssert.ThrowingCallable() { - public void call() { - mock.clear(); - } + assertThatThrownBy( + () -> { + mock.clear(); }) .isInstanceOf(ExceptionOne.class); } @@ -125,43 +112,51 @@ public void throws_new_exception_consecutively_from_class_with_doThrow() { } @Test - public void shouldStubWithThrowable() throws Exception { + public void shouldStubWithThrowable() { IllegalArgumentException expected = new IllegalArgumentException("thrown by mock"); when(mock.add("throw")).thenThrow(expected); - exception.expect(sameInstance(expected)); - mock.add("throw"); + assertThatThrownBy( + () -> { + mock.add("throw"); + }) + .isEqualTo(expected); } @Test - public void shouldSetThrowableToVoidMethod() throws Exception { + public void shouldSetThrowableToVoidMethod() { IllegalArgumentException expected = new IllegalArgumentException("thrown by mock"); doThrow(expected).when(mock).clear(); - exception.expect(sameInstance(expected)); - - mock.clear(); + assertThatThrownBy( + () -> { + mock.clear(); + }) + .isEqualTo(expected); } @Test - public void shouldLastStubbingVoidBeImportant() throws Exception { + public void shouldLastStubbingVoidBeImportant() { doThrow(new ExceptionOne()).when(mock).clear(); doThrow(new ExceptionTwo()).when(mock).clear(); - exception.expect(ExceptionTwo.class); - - mock.clear(); + assertThatThrownBy( + () -> { + mock.clear(); + }) + .isInstanceOf(ExceptionTwo.class); } @Test - public void shouldFailStubbingThrowableOnTheSameInvocationDueToAcceptableLimitation() - throws Exception { + public void shouldFailStubbingThrowableOnTheSameInvocationDueToAcceptableLimitation() { when(mock.size()).thenThrow(new ExceptionOne()); - exception.expect(ExceptionOne.class); - - when(mock.size()).thenThrow(new ExceptionTwo()); + assertThatThrownBy( + () -> { + when(mock.size()).thenThrow(new ExceptionTwo()); + }) + .isInstanceOf(ExceptionOne.class); } @Test @@ -171,160 +166,199 @@ public void shouldAllowSettingCheckedException() throws Exception { when(reader.read()).thenThrow(ioException); - exception.expect(sameInstance(ioException)); - - reader.read(); + assertThatThrownBy( + () -> { + reader.read(); + }) + .isEqualTo(ioException); } @Test - public void shouldAllowSettingError() throws Exception { + public void shouldAllowSettingError() { Error error = new Error(); when(mock.add("quake")).thenThrow(error); - exception.expect(Error.class); - - mock.add("quake"); + assertThatThrownBy( + () -> { + mock.add("quake"); + }) + .isEqualTo(error); } @Test public void shouldNotAllowNullExceptionType() { - exception.expect(MockitoException.class); - exception.expectMessage("Cannot stub with null throwable"); - - when(mock.add(null)).thenThrow((Exception) null); + assertThatThrownBy( + () -> { + when(mock.add(null)).thenThrow((Exception) null); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("Cannot stub with null throwable"); } @Test public void shouldInstantiateExceptionClassOnInteraction() { when(mock.add(null)).thenThrow(NaughtyException.class); - exception.expect(NaughtyException.class); - - mock.add(null); + assertThatThrownBy( + () -> { + mock.add(null); + }) + .isInstanceOf(NaughtyException.class); } @Test public void shouldInstantiateExceptionClassWithOngoingStubbingOnInteraction() { doThrow(NaughtyException.class).when(mock).add(null); - exception.expect(NaughtyException.class); - - mock.add(null); + assertThatThrownBy( + () -> { + mock.add(null); + }) + .isInstanceOf(NaughtyException.class); } @Test public void shouldNotAllowSettingInvalidCheckedException() { - exception.expect(MockitoException.class); - exception.expectMessage("Checked exception is invalid for this method"); - - when(mock.add("monkey island")).thenThrow(new Exception()); + assertThatThrownBy( + () -> { + when(mock.add("monkey island")).thenThrow(new Exception()); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("Checked exception is invalid for this method"); } @Test public void shouldNotAllowSettingNullThrowable() { - exception.expect(MockitoException.class); - exception.expectMessage("Cannot stub with null throwable"); - - when(mock.add("monkey island")).thenThrow((Throwable) null); + assertThatThrownBy( + () -> { + when(mock.add("monkey island")).thenThrow((Throwable) null); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("Cannot stub with null throwable"); } @Test public void shouldNotAllowSettingNullThrowableArray() { - exception.expect(MockitoException.class); - exception.expectMessage("Cannot stub with null throwable"); - - when(mock.add("monkey island")).thenThrow((Throwable[]) null); + assertThatThrownBy( + () -> { + when(mock.add("monkey island")).thenThrow((Throwable[]) null); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("Cannot stub with null throwable"); } @Test public void shouldNotAllowSettingNullThrowableClass() { - exception.expect(MockitoException.class); - exception.expectMessage("Exception type cannot be null"); - - when(mock.isEmpty()).thenThrow((Class) null); + assertThatThrownBy( + () -> { + when(mock.isEmpty()).thenThrow((Class) null); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("Exception type cannot be null"); } @Test public void shouldNotAllowSettingNullThrowableClasses() { - exception.expect(MockitoException.class); - exception.expectMessage("Exception type cannot be null"); - - when(mock.isEmpty()).thenThrow(RuntimeException.class, (Class[]) null); + assertThatThrownBy( + () -> { + when(mock.isEmpty()).thenThrow(RuntimeException.class, (Class[]) null); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("Exception type cannot be null"); } @Test public void shouldNotAllowSettingNullVarArgThrowableClass() { - exception.expect(MockitoException.class); - exception.expectMessage("Exception type cannot be null"); - - when(mock.isEmpty()).thenThrow(RuntimeException.class, (Class) null); + assertThatThrownBy( + () -> { + when(mock.isEmpty()).thenThrow(RuntimeException.class, (Class) null); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("Exception type cannot be null"); } @Test public void doThrowShouldNotAllowSettingNullThrowableClass() { - exception.expect(MockitoException.class); - exception.expectMessage("Exception type cannot be null"); - - doThrow((Class) null).when(mock).isEmpty(); + assertThatThrownBy( + () -> { + doThrow((Class) null).when(mock).isEmpty(); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("Exception type cannot be null"); } @Test - public void doThrowShouldNotAllowSettingNullThrowableClasses() throws Exception { - exception.expect(MockitoException.class); - exception.expectMessage("Exception type cannot be null"); - - doThrow(RuntimeException.class, (Class) null).when(mock).isEmpty(); + public void doThrowShouldNotAllowSettingNullThrowableClasses() { + assertThatThrownBy( + () -> { + doThrow(RuntimeException.class, (Class) null).when(mock).isEmpty(); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("Exception type cannot be null"); } @Test - public void doThrowShouldNotAllowSettingNullVarArgThrowableClasses() throws Exception { - exception.expect(MockitoException.class); - exception.expectMessage("Exception type cannot be null"); - - doThrow(RuntimeException.class, (Class[]) null).when(mock).isEmpty(); + public void doThrowShouldNotAllowSettingNullVarArgThrowableClasses() { + assertThatThrownBy( + () -> { + doThrow(RuntimeException.class, (Class[]) null).when(mock).isEmpty(); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("Exception type cannot be null"); } @Test - public void shouldNotAllowSettingNullVarArgsThrowableClasses() throws Exception { - exception.expect(MockitoException.class); - exception.expectMessage("Exception type cannot be null"); - - when(mock.isEmpty()).thenThrow(RuntimeException.class, (Class[]) null); + public void shouldNotAllowSettingNullVarArgsThrowableClasses() { + assertThatThrownBy( + () -> { + when(mock.isEmpty()) + .thenThrow( + RuntimeException.class, + (Class[]) null); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("Exception type cannot be null"); } @Test - public void shouldNotAllowDifferentCheckedException() throws Exception { + public void shouldNotAllowDifferentCheckedException() { IMethods mock = mock(IMethods.class); - exception.expect(MockitoException.class); - exception.expectMessage("Checked exception is invalid for this method"); - - when(mock.throwsIOException(0)).thenThrow(CheckedException.class); + assertThatThrownBy( + () -> { + when(mock.throwsIOException(0)).thenThrow(CheckedException.class); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("Checked exception is invalid for this method"); } @Test - public void shouldNotAllowCheckedExceptionWhenErrorIsDeclared() throws Exception { + public void shouldNotAllowCheckedExceptionWhenErrorIsDeclared() { IMethods mock = mock(IMethods.class); - exception.expect(MockitoException.class); - exception.expectMessage("Checked exception is invalid for this method"); - - when(mock.throwsError(0)).thenThrow(CheckedException.class); + assertThatThrownBy( + () -> { + when(mock.throwsError(0)).thenThrow(CheckedException.class); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("Checked exception is invalid for this method"); } @Test - public void shouldNotAllowCheckedExceptionWhenNothingIsDeclared() throws Exception { + public void shouldNotAllowCheckedExceptionWhenNothingIsDeclared() { IMethods mock = mock(IMethods.class); - exception.expect(MockitoException.class); - exception.expectMessage("Checked exception is invalid for this method"); - - when(mock.throwsNothing(true)).thenThrow(CheckedException.class); + assertThatThrownBy( + () -> { + when(mock.throwsNothing(true)).thenThrow(CheckedException.class); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("Checked exception is invalid for this method"); } @Test - public void shouldMixThrowablesAndReturnsOnDifferentMocks() throws Exception { + public void shouldMixThrowablesAndReturnsOnDifferentMocks() { when(mock.add("ExceptionOne")).thenThrow(new ExceptionOne()); when(mock.getLast()).thenReturn("last"); doThrow(new ExceptionTwo()).when(mock).clear(); diff --git a/src/test/java/org/mockitousage/verification/BasicVerificationInOrderTest.java b/src/test/java/org/mockitousage/verification/BasicVerificationInOrderTest.java index b0c4b2d236..80d02e32a9 100644 --- a/src/test/java/org/mockitousage/verification/BasicVerificationInOrderTest.java +++ b/src/test/java/org/mockitousage/verification/BasicVerificationInOrderTest.java @@ -5,8 +5,14 @@ package org.mockitousage.verification; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; import org.junit.Before; import org.junit.Test; @@ -101,14 +107,36 @@ public void shouldFailWhenLastMockCalledTwice() { } } - @Test(expected = VerificationInOrderFailure.class) + @Test public void shouldFailOnFirstMethodBecauseOneInvocationWanted() { - inOrder.verify(mockOne, times(0)).simpleMethod(1); + assertThatThrownBy( + () -> { + inOrder.verify(mockOne, times(0)).simpleMethod(1); + }) + .isInstanceOf(VerificationInOrderFailure.class) + .hasMessageContainingAll( + "Verification in order failure:", + "iMethods.simpleMethod(1);", + "Wanted 0 times:", + "-> at ", + "But was 1 time:", + "-> at "); } - @Test(expected = VerificationInOrderFailure.class) + @Test public void shouldFailOnFirstMethodBecauseOneInvocationWantedAgain() { - inOrder.verify(mockOne, times(2)).simpleMethod(1); + assertThatThrownBy( + () -> { + inOrder.verify(mockOne, times(2)).simpleMethod(1); + }) + .isInstanceOf(VerificationInOrderFailure.class) + .hasMessageContainingAll( + "Verification in order failure:", + "iMethods.simpleMethod(1);", + "Wanted 2 times:", + "-> at ", + "But was 1 time:", + "-> at "); } @Test @@ -159,14 +187,56 @@ public void shouldFailOnLastMethodBecauseOneInvocationWantedAgain() { /* ------------- */ - @Test(expected = ArgumentsAreDifferent.class) + @Test public void shouldFailOnFirstMethodBecauseDifferentArgsWanted() { - inOrder.verify(mockOne).simpleMethod(100); + assertThatThrownBy( + () -> { + inOrder.verify(mockOne).simpleMethod(100); + }) + .isInstanceOf(ArgumentsAreDifferent.class) + .hasMessageContainingAll( + "Argument(s) are different! Wanted:", + "iMethods.simpleMethod(100);", + "-> at ", + "Actual invocations have different arguments:", + "iMethods.simpleMethod(1);", + "-> at ", + "iMethods.simpleMethod(2);", + "-> at ", + "iMethods.simpleMethod(2);", + "-> at ", + "iMethods.simpleMethod(3);", + "-> at ", + "iMethods.simpleMethod(2);", + "-> at ", + "iMethods.simpleMethod(4);", + "-> at "); } - @Test(expected = WantedButNotInvoked.class) + @Test public void shouldFailOnFirstMethodBecauseDifferentMethodWanted() { - inOrder.verify(mockOne).oneArg(true); + assertThatThrownBy( + () -> { + inOrder.verify(mockOne).oneArg(true); + }) + .isInstanceOf(WantedButNotInvoked.class) + .hasMessageContainingAll( + "Wanted but not invoked:", + "iMethods.oneArg(true);", + "-> at ", + "However, there were exactly 6 interactions with this mock:", + "iMethods.simpleMethod(1);", + "-> at ", + "iMethods.simpleMethod(2);", + "-> at ", + "iMethods.simpleMethod(2);", + "-> at ", + "iMethods.simpleMethod(3);", + "-> at ", + "iMethods.simpleMethod(2);", + "-> at ", + "iMethods.simpleMethod(4);", + "-> at "); } @Test @@ -261,15 +331,38 @@ public void shouldFailOnVerifyNoMoreInteractions() { } } - @Test(expected = NoInteractionsWanted.class) + @Test public void shouldFailOnVerifyNoInteractions() { - verifyNoInteractions(mockOne); + assertThatThrownBy( + () -> { + verifyNoInteractions(mockOne); + }) + .isInstanceOf(NoInteractionsWanted.class) + .hasMessageContainingAll( + "No interactions wanted here:", + "-> at ", + "But found these interactions on mock 'iMethods':", + "-> at ", + "-> at ", + "***", + "For your reference, here is the list of all invocations ([?] - means unverified).", + "1. [?]-> at ", + "2. [?]-> at "); } @SuppressWarnings({"all", "CheckReturnValue", "MockitoUsage"}) - @Test(expected = MockitoException.class) + @Test public void shouldScreamWhenNullPassed() { - inOrder((Object[]) null); + assertThatThrownBy( + () -> { + inOrder((Object[]) null); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "Method requires argument(s)!", + "Pass mocks that require verification in order.", + "For example:", + " InOrder inOrder = inOrder(mockOne, mockTwo);"); } @Test diff --git a/src/test/java/org/mockitousage/verification/BasicVerificationTest.java b/src/test/java/org/mockitousage/verification/BasicVerificationTest.java index 2f2f6b37a9..70df2b178b 100644 --- a/src/test/java/org/mockitousage/verification/BasicVerificationTest.java +++ b/src/test/java/org/mockitousage/verification/BasicVerificationTest.java @@ -6,11 +6,14 @@ import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; import java.util.List; -import org.assertj.core.api.ThrowableAssert; import org.junit.Test; import org.mockito.Mock; import org.mockito.exceptions.verification.NoInteractionsWanted; @@ -26,7 +29,7 @@ public class BasicVerificationTest extends TestBase { @Mock private List mockTwo; @Test - public void shouldVerify() throws Exception { + public void shouldVerify() { mock.clear(); verify(mock).clear(); @@ -36,30 +39,36 @@ public void shouldVerify() throws Exception { verifyNoMoreInteractions(mock); } - @Test(expected = WantedButNotInvoked.class) - public void shouldFailVerification() throws Exception { - verify(mock).clear(); + @Test + public void shouldFailVerification() { + assertThatThrownBy( + () -> { + verify(mock).clear(); + }) + .isInstanceOf(WantedButNotInvoked.class) + .hasMessageContainingAll( + "Wanted but not invoked:", + "mock.clear();", + "-> at ", + "Actually, there were zero interactions with this mock."); } @Test - public void shouldFailVerificationOnMethodArgument() throws Exception { + public void shouldFailVerificationOnMethodArgument() { mock.clear(); mock.add("foo"); verify(mock).clear(); assertThatThrownBy( - new ThrowableAssert.ThrowingCallable() { - @Override - public void call() { - verify(mock).add("bar"); - } + () -> { + verify(mock).add("bar"); }) .isInstanceOf(ArgumentsAreDifferent.class); } @Test - public void shouldFailOnWrongMethod() throws Exception { + public void shouldFailOnWrongMethod() { mock.clear(); mock.clear(); @@ -75,7 +84,7 @@ public void shouldFailOnWrongMethod() throws Exception { } @Test - public void shouldDetectRedundantInvocation() throws Exception { + public void shouldDetectRedundantInvocation() { mock.clear(); mock.add("foo"); mock.add("bar"); @@ -91,7 +100,7 @@ public void shouldDetectRedundantInvocation() throws Exception { } @Test - public void shouldDetectWhenInvokedMoreThanOnce() throws Exception { + public void shouldDetectWhenInvokedMoreThanOnce() { mock.add("foo"); mock.clear(); mock.clear(); @@ -106,7 +115,7 @@ public void shouldDetectWhenInvokedMoreThanOnce() throws Exception { } @Test - public void shouldVerifyStubbedMethods() throws Exception { + public void shouldVerifyStubbedMethods() { when(mock.add("test")).thenReturn(Boolean.FALSE); mock.add("test"); @@ -115,7 +124,7 @@ public void shouldVerifyStubbedMethods() throws Exception { } @Test - public void shouldDetectWhenOverloadedMethodCalled() throws Exception { + public void shouldDetectWhenOverloadedMethodCalled() { IMethods mockThree = mock(IMethods.class); mockThree.varargs((Object[]) new Object[] {}); diff --git a/src/test/java/org/mockitousage/verification/NoMoreInteractionsVerificationTest.java b/src/test/java/org/mockitousage/verification/NoMoreInteractionsVerificationTest.java index 72c75a909b..38ad1dff68 100644 --- a/src/test/java/org/mockitousage/verification/NoMoreInteractionsVerificationTest.java +++ b/src/test/java/org/mockitousage/verification/NoMoreInteractionsVerificationTest.java @@ -5,8 +5,14 @@ package org.mockitousage.verification; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; import java.util.LinkedList; import java.util.List; @@ -29,7 +35,7 @@ public void setup() { } @Test - public void shouldStubbingNotRegisterRedundantInteractions() throws Exception { + public void shouldStubbingNotRegisterRedundantInteractions() { when(mock.add("one")).thenReturn(true); when(mock.add("two")).thenReturn(true); @@ -40,7 +46,7 @@ public void shouldStubbingNotRegisterRedundantInteractions() throws Exception { } @Test - public void shouldVerifyWhenWantedNumberOfInvocationsUsed() throws Exception { + public void shouldVerifyWhenWantedNumberOfInvocationsUsed() { mock.add("one"); mock.add("one"); mock.add("one"); @@ -51,7 +57,7 @@ public void shouldVerifyWhenWantedNumberOfInvocationsUsed() throws Exception { } @Test - public void shouldFailNoMoreInteractionsVerification() throws Exception { + public void shouldFailNoMoreInteractionsVerification() { mock.clear(); try { @@ -62,7 +68,7 @@ public void shouldFailNoMoreInteractionsVerification() throws Exception { } @Test - public void shouldFailNoInteractionsVerification() throws Exception { + public void shouldFailNoInteractionsVerification() { mock.clear(); try { @@ -73,7 +79,7 @@ public void shouldFailNoInteractionsVerification() throws Exception { } @Test - public void shouldPrintAllInvocationsWhenVerifyingNoMoreInvocations() throws Exception { + public void shouldPrintAllInvocationsWhenVerifyingNoMoreInvocations() { mock.add(1); mock.add(2); mock.clear(); @@ -88,7 +94,7 @@ public void shouldPrintAllInvocationsWhenVerifyingNoMoreInvocations() throws Exc } @Test - public void shouldNotContainAllInvocationsWhenSingleUnwantedFound() throws Exception { + public void shouldNotContainAllInvocationsWhenSingleUnwantedFound() { mock.add(1); try { @@ -100,7 +106,7 @@ public void shouldNotContainAllInvocationsWhenSingleUnwantedFound() throws Excep } @Test - public void shouldVerifyOneMockButFailOnOther() throws Exception { + public void shouldVerifyOneMockButFailOnOther() { List list = mock(List.class); Map map = mock(Map.class); @@ -120,7 +126,7 @@ public void shouldVerifyOneMockButFailOnOther() throws Exception { } @Test - public void shouldVerifyOneMockButFailOnOtherVerifyNoInteractions() throws Exception { + public void shouldVerifyOneMockButFailOnOtherVerifyNoInteractions() { List list = mock(List.class); Map map = mock(Map.class); @@ -139,9 +145,18 @@ public void shouldVerifyOneMockButFailOnOtherVerifyNoInteractions() throws Excep } } - @SuppressWarnings("all") - @Test(expected = MockitoException.class) - public void verifyNoMoreInteractionsShouldScreamWhenNullPassed() throws Exception { - verifyNoMoreInteractions((Object[]) null); + // @SuppressWarnings("all") + @Test + public void verifyNoMoreInteractionsShouldScreamWhenNullPassed() { + assertThatThrownBy( + () -> { + verifyNoMoreInteractions((Object[]) null); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "Method requires argument(s)!", + "Pass mocks that should be verified, e.g:", + " verifyNoMoreInteractions(mockOne, mockTwo);", + " verifyNoInteractions(mockOne, mockTwo);"); } } diff --git a/src/test/java/org/mockitousage/verification/RelaxedVerificationInOrderTest.java b/src/test/java/org/mockitousage/verification/RelaxedVerificationInOrderTest.java index ea172ce0ac..d947dc8ee4 100644 --- a/src/test/java/org/mockitousage/verification/RelaxedVerificationInOrderTest.java +++ b/src/test/java/org/mockitousage/verification/RelaxedVerificationInOrderTest.java @@ -4,8 +4,14 @@ */ package org.mockitousage.verification; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.atLeastOnce; +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.verifyNoMoreInteractions; import org.junit.Before; import org.junit.Test; @@ -120,9 +126,22 @@ public void shouldVerifyInteractionsFromFirstChunk() { } } - @Test(expected = VerificationInOrderFailure.class) + @Test public void shouldFailVerificationOfNonFirstChunk() { - inOrder.verify(mockTwo, times(1)).simpleMethod(2); + assertThatThrownBy( + () -> { + inOrder.verify(mockTwo, times(1)).simpleMethod(2); + }) + .isInstanceOf(VerificationInOrderFailure.class) + .hasMessageContainingAll( + "Verification in order failure:", + "iMethods.simpleMethod(2);", + "Wanted 1 time:", + "-> at ", + "But was 3 times:", + "-> at ", + "-> at ", + "-> at "); } @Test @@ -185,9 +204,30 @@ public void shouldVerifyMockTwoCalledAtLeastOnce() { inOrder.verify(mockTwo, atLeastOnce()).simpleMethod(2); } - @Test(expected = WantedButNotInvoked.class) + @Test public void shouldFailOnWrongMethodCalledOnMockTwo() { - inOrder.verify(mockTwo, atLeastOnce()).differentMethod(); + assertThatThrownBy( + () -> { + inOrder.verify(mockTwo, atLeastOnce()).differentMethod(); + }) + .isInstanceOf(WantedButNotInvoked.class) + .hasMessageContainingAll( + "Wanted but not invoked:", + "iMethods.differentMethod();", + "-> at ", + "However, there were exactly 6 interactions with this mock:", + "iMethods.simpleMethod(1);", + "-> at ", + "iMethods.simpleMethod(2);", + "-> at ", + "iMethods.simpleMethod(2);", + "-> at ", + "iMethods.simpleMethod(3);", + "-> at ", + "iMethods.simpleMethod(2);", + "-> at ", + "iMethods.simpleMethod(4);", + "-> at "); } @Test @@ -212,9 +252,22 @@ public void shouldFailTimesZeroInOrder() { } } - @Test(expected = VerificationInOrderFailure.class) + @Test public void shouldFailWhenMockTwoWantedZeroTimes() { - inOrder.verify(mockTwo, times(0)).simpleMethod(2); + assertThatThrownBy( + () -> { + inOrder.verify(mockTwo, times(0)).simpleMethod(2); + }) + .isInstanceOf(VerificationInOrderFailure.class) + .hasMessageContainingAll( + "Verification in order failure:", + "iMethods.simpleMethod(2);", + "Wanted 0 times:", + "-> at ", + "But was 3 times:", + "-> at ", + "-> at ", + "-> at "); } @Test diff --git a/src/test/java/org/mockitousage/verification/VerificationExcludingStubsTest.java b/src/test/java/org/mockitousage/verification/VerificationExcludingStubsTest.java index 4a8ad677ed..1494d081a3 100644 --- a/src/test/java/org/mockitousage/verification/VerificationExcludingStubsTest.java +++ b/src/test/java/org/mockitousage/verification/VerificationExcludingStubsTest.java @@ -4,8 +4,13 @@ */ package org.mockitousage.verification; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; -import static org.mockito.Mockito.*; +import static org.mockito.Mockito.ignoreStubs; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; +import static org.mockito.Mockito.when; import org.junit.Test; import org.mockito.InOrder; @@ -21,7 +26,7 @@ public class VerificationExcludingStubsTest extends TestBase { @Mock IMethods mock; @Test - public void shouldAllowToExcludeStubsForVerification() throws Exception { + public void shouldAllowToExcludeStubsForVerification() { // given when(mock.simpleMethod()).thenReturn("foo"); @@ -45,7 +50,7 @@ public void shouldAllowToExcludeStubsForVerification() throws Exception { } @Test - public void shouldExcludeFromVerificationInOrder() throws Exception { + public void shouldExcludeFromVerificationInOrder() { // given when(mock.simpleMethod()).thenReturn("foo"); @@ -62,13 +67,23 @@ public void shouldExcludeFromVerificationInOrder() throws Exception { verifyNoMoreInteractions(mock); } - @Test(expected = NotAMockException.class) - public void shouldIgnoringStubsDetectNulls() throws Exception { - Object ignored = ignoreStubs(mock, null); + @Test + public void shouldIgnoringStubsDetectNulls() { + assertThatThrownBy( + () -> { + Object ignored = ignoreStubs(mock, null); + }) + .isInstanceOf(NotAMockException.class) + .hasMessage("Argument should be a mock, but is null!"); } - @Test(expected = NotAMockException.class) - public void shouldIgnoringStubsDetectNonMocks() throws Exception { - Object ignored = ignoreStubs(mock, new Object()); + @Test + public void shouldIgnoringStubsDetectNonMocks() { + assertThatThrownBy( + () -> { + Object ignored = ignoreStubs(mock, new Object()); + }) + .isInstanceOf(NotAMockException.class) + .hasMessage("Argument should be a mock, but is: class java.lang.Object"); } } diff --git a/src/test/java/org/mockitousage/verification/VerificationInOrderMixedWithOrdiraryVerificationTest.java b/src/test/java/org/mockitousage/verification/VerificationInOrderMixedWithOrdinaryVerificationTest.java similarity index 81% rename from src/test/java/org/mockitousage/verification/VerificationInOrderMixedWithOrdiraryVerificationTest.java rename to src/test/java/org/mockitousage/verification/VerificationInOrderMixedWithOrdinaryVerificationTest.java index c03d63fd1a..8a978e4cb8 100644 --- a/src/test/java/org/mockitousage/verification/VerificationInOrderMixedWithOrdiraryVerificationTest.java +++ b/src/test/java/org/mockitousage/verification/VerificationInOrderMixedWithOrdinaryVerificationTest.java @@ -4,8 +4,16 @@ */ package org.mockitousage.verification; -import static org.junit.Assert.*; -import static org.mockito.Mockito.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotSame; +import static org.junit.Assert.fail; +import static org.mockito.Mockito.atLeastOnce; +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.verifyNoMoreInteractions; import org.junit.Before; import org.junit.Test; @@ -16,7 +24,7 @@ import org.mockitousage.IMethods; import org.mockitoutil.TestBase; -public class VerificationInOrderMixedWithOrdiraryVerificationTest extends TestBase { +public class VerificationInOrderMixedWithOrdinaryVerificationTest extends TestBase { private IMethods mockOne; private IMethods mockTwo; @@ -121,9 +129,18 @@ public void shouldFailOnLastInvocationTooEarly() { } } - @Test(expected = MockitoException.class) + @Test public void shouldScreamWhenUnfamiliarMockPassedToInOrderObject() { - inOrder.verify(mockTwo, atLeastOnce()).simpleMethod(1); + assertThatThrownBy( + () -> { + inOrder.verify(mockTwo, atLeastOnce()).simpleMethod(1); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "InOrder can only verify mocks that were passed in during creation of InOrder.", + "For example:", + " InOrder inOrder = inOrder(mockOne);", + " inOrder.verify(mockOne).doStuff();"); } @Test diff --git a/src/test/java/org/mockitousage/verification/VerificationInOrderWithCallsTest.java b/src/test/java/org/mockitousage/verification/VerificationInOrderWithCallsTest.java index ce5f742bbc..f2861b7929 100644 --- a/src/test/java/org/mockitousage/verification/VerificationInOrderWithCallsTest.java +++ b/src/test/java/org/mockitousage/verification/VerificationInOrderWithCallsTest.java @@ -4,11 +4,15 @@ */ package org.mockitousage.verification; -import static org.mockito.Mockito.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.calls; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; -import org.junit.Rule; import org.junit.Test; -import org.junit.rules.ExpectedException; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.exceptions.base.MockitoException; @@ -21,7 +25,6 @@ public class VerificationInOrderWithCallsTest extends TestBase { @Mock private IMethods mockOne; @Mock private IMethods mockTwo; - @Rule public ExpectedException exceptionRule = ExpectedException.none(); @Test public void shouldFailWhenMethodNotCalled() { @@ -30,15 +33,16 @@ public void shouldFailWhenMethodNotCalled() { InOrder verifier = inOrder(mockOne); verifier.verify(mockOne, calls(1)).oneArg(1); - exceptionRule.expect(VerificationInOrderFailure.class); - exceptionRule.expectMessage("Verification in order failure"); - exceptionRule.expectMessage("Wanted but not invoked"); - exceptionRule.expectMessage("mockOne.oneArg(2)"); - - // When - verifier.verify(mockOne, calls(1)).oneArg(2); - - // Then - expected exception thrown + // When / Then - expected exception thrown + assertThatThrownBy( + () -> { + verifier.verify(mockOne, calls(1)).oneArg(2); + }) + .isInstanceOf(VerificationInOrderFailure.class) + .hasMessageContainingAll( + "Verification in order failure", + "Wanted but not invoked", + "mockOne.oneArg(2)"); } @Test @@ -50,16 +54,17 @@ public void shouldFailWhenMethodCalledTooFewTimes() { InOrder verifier = inOrder(mockOne); verifier.verify(mockOne, calls(1)).oneArg(1); - exceptionRule.expect(VerificationInOrderFailure.class); - exceptionRule.expectMessage("Verification in order failure"); - exceptionRule.expectMessage("mockOne.oneArg(2)"); - exceptionRule.expectMessage("Wanted 2 times"); - exceptionRule.expectMessage("But was 1 time"); - - // When - verifier.verify(mockOne, calls(2)).oneArg(2); - - // Then - expected exception thrown + // When / Then - expected exception thrown + assertThatThrownBy( + () -> { + verifier.verify(mockOne, calls(2)).oneArg(2); + }) + .isInstanceOf(VerificationInOrderFailure.class) + .hasMessageContainingAll( + "Verification in order failure", + "mockOne.oneArg(2)", + "Wanted 2 times", + "But was 1 time"); } @Test @@ -71,15 +76,16 @@ public void shouldFailWhenSingleMethodCallsAreOutOfSequence() { InOrder verifier = inOrder(mockOne); verifier.verify(mockOne, calls(1)).oneArg(2); - exceptionRule.expect(VerificationInOrderFailure.class); - exceptionRule.expectMessage("Verification in order failure"); - exceptionRule.expectMessage("Wanted but not invoked"); - exceptionRule.expectMessage("mockOne.oneArg(1)"); - - // When - verifier.verify(mockOne, calls(1)).oneArg(1); - - // Then - expected exception thrown + // When / Then - expected exception thrown + assertThatThrownBy( + () -> { + verifier.verify(mockOne, calls(1)).oneArg(1); + }) + .isInstanceOf(VerificationInOrderFailure.class) + .hasMessageContainingAll( + "Verification in order failure", + "Wanted but not invoked", + "mockOne.oneArg(1)"); } @Test @@ -91,15 +97,16 @@ public void shouldFailWhenDifferentMethodCallsAreOutOfSequence() { InOrder verifier = inOrder(mockOne); verifier.verify(mockOne, calls(1)).voidMethod(); - exceptionRule.expect(VerificationInOrderFailure.class); - exceptionRule.expectMessage("Verification in order failure"); - exceptionRule.expectMessage("Wanted but not invoked"); - exceptionRule.expectMessage("mockOne.oneArg(1)"); - - // When - verifier.verify(mockOne, calls(1)).oneArg(1); - - // Then - expected exception thrown + // When / Then - expected exception thrown + assertThatThrownBy( + () -> { + verifier.verify(mockOne, calls(1)).oneArg(1); + }) + .isInstanceOf(VerificationInOrderFailure.class) + .hasMessageContainingAll( + "Verification in order failure", + "Wanted but not invoked", + "mockOne.oneArg(1)"); } @Test @@ -111,15 +118,16 @@ public void shouldFailWhenMethodCallsOnDifferentMocksAreOutOfSequence() { InOrder verifier = inOrder(mockOne, mockTwo); verifier.verify(mockTwo, calls(1)).voidMethod(); - exceptionRule.expect(VerificationInOrderFailure.class); - exceptionRule.expectMessage("Verification in order failure"); - exceptionRule.expectMessage("Wanted but not invoked"); - exceptionRule.expectMessage("mockOne.voidMethod()"); - - // When - verifier.verify(mockOne, calls(1)).voidMethod(); - - // Then - expected exception thrown + // When / Then - expected exception thrown + assertThatThrownBy( + () -> { + verifier.verify(mockOne, calls(1)).voidMethod(); + }) + .isInstanceOf(VerificationInOrderFailure.class) + .hasMessageContainingAll( + "Verification in order failure", + "Wanted but not invoked", + "mockOne.voidMethod()"); } @Test @@ -216,12 +224,12 @@ public void shouldNotVerifySkippedCallsWhenFewerCallsForSingleMethod() { verifier.verify(mockOne, calls(1)).oneArg(2); verifier.verify(mockOne, calls(1)).oneArg(1); - exceptionRule.expect(NoInteractionsWanted.class); - - // When - verifyNoMoreInteractions(mockOne); - - // Then - expected exception thrown + // When / Then - expected exception thrown + assertThatThrownBy( + () -> { + verifyNoMoreInteractions(mockOne); + }) + .isInstanceOf(NoInteractionsWanted.class); } @Test @@ -235,13 +243,13 @@ public void shouldNotVerifySkippedCallsInInOrderWhenFewerCallsForSingleMethod() verifier.verify(mockOne, calls(1)).oneArg(1); verifier.verify(mockOne, calls(1)).oneArg(2); - exceptionRule.expect(VerificationInOrderFailure.class); - exceptionRule.expectMessage("No interactions wanted here"); - - // When - verifier.verifyNoMoreInteractions(); - - // Then - expected exception thrown + // When / Then - expected exception thrown + assertThatThrownBy( + () -> { + verifier.verifyNoMoreInteractions(); + }) + .isInstanceOf(VerificationInOrderFailure.class) + .hasMessageContaining("No interactions wanted here"); } @Test @@ -277,12 +285,12 @@ public void shouldNotVerifySkippedCallsWhenFewerCallsForDifferentMethods() { verifier.verify(mockOne, calls(1)).voidMethod(); verifier.verify(mockOne, calls(1)).oneArg(1); - exceptionRule.expect(NoInteractionsWanted.class); - - // When - verifyNoMoreInteractions(mockOne); - - // Then - no exception thrown + // When / Then - no exception thrown + assertThatThrownBy( + () -> { + verifyNoMoreInteractions(mockOne); + }) + .isInstanceOf(NoInteractionsWanted.class); } @Test @@ -296,13 +304,13 @@ public void shouldNotVerifySkippedCallsInInOrderWhenFewerCallsForDifferentMethod verifier.verify(mockOne, calls(1)).oneArg(1); verifier.verify(mockOne, calls(1)).voidMethod(); - exceptionRule.expect(VerificationInOrderFailure.class); - exceptionRule.expectMessage("No interactions wanted here"); - - // When - verifier.verifyNoMoreInteractions(); - - // Then - expected exception thrown + // When / Then - expected exception thrown + assertThatThrownBy( + () -> { + verifier.verifyNoMoreInteractions(); + }) + .isInstanceOf(VerificationInOrderFailure.class) + .hasMessageContaining("No interactions wanted here"); } @Test @@ -338,12 +346,12 @@ public void shouldNotVerifySkippedCallsWhenFewerCallsForMethodsOnDifferentMocks( verifier.verify(mockTwo, calls(1)).voidMethod(); verifier.verify(mockOne, calls(1)).voidMethod(); - exceptionRule.expect(NoInteractionsWanted.class); - - // When - verifyNoMoreInteractions(mockTwo); - - // Then - expected exception thrown + // When / Then - expected exception thrown + assertThatThrownBy( + () -> { + verifyNoMoreInteractions(mockTwo); + }) + .isInstanceOf(NoInteractionsWanted.class); } @Test @@ -357,13 +365,13 @@ public void shouldNotVerifySkippedCallsInInOrderWhenFewerCallsForMethodsOnDiffer verifier.verify(mockOne, calls(1)).voidMethod(); verifier.verify(mockTwo, calls(1)).voidMethod(); - exceptionRule.expect(VerificationInOrderFailure.class); - exceptionRule.expectMessage("No interactions wanted here"); - - // When - verifier.verifyNoMoreInteractions(); - - // Then - expected exception thrown + // When / Then - expected exception thrown + assertThatThrownBy( + () -> { + verifier.verifyNoMoreInteractions(); + }) + .isInstanceOf(VerificationInOrderFailure.class) + .hasMessageContaining("No interactions wanted here"); } @Test @@ -457,38 +465,41 @@ public void shouldVerifyWithTimesAfterCallsInSameChunk() { public void shouldFailToCreateCallsWithZeroArgument() { // Given InOrder verifier = inOrder(mockOne); - exceptionRule.expect(MockitoException.class); - exceptionRule.expectMessage("Negative and zero values are not allowed here"); - // When - verifier.verify(mockOne, calls(0)).voidMethod(); - - // Then - expected exception thrown + // When / Then - expected exception thrown + assertThatThrownBy( + () -> { + verifier.verify(mockOne, calls(0)).voidMethod(); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("Negative and zero values are not allowed here"); } @Test public void shouldFailToCreateCallsWithNegativeArgument() { // Given InOrder verifier = inOrder(mockOne); - exceptionRule.expect(MockitoException.class); - exceptionRule.expectMessage("Negative and zero values are not allowed here"); - - // When - verifier.verify(mockOne, calls(-1)).voidMethod(); - // Then - expected exception thrown + // When / Then - expected exception thrown + assertThatThrownBy( + () -> { + verifier.verify(mockOne, calls(-1)).voidMethod(); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("Negative and zero values are not allowed here"); } @Test public void shouldFailToCreateCallsForNonInOrderVerification() { // Given mockOne.voidMethod(); - exceptionRule.expect(MockitoException.class); - exceptionRule.expectMessage("calls is only intended to work with InOrder"); - - // When - verify(mockOne, calls(1)).voidMethod(); - // Then - expected exception thrown + // When / Then - expected exception thrown + assertThatThrownBy( + () -> { + verify(mockOne, calls(1)).voidMethod(); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("calls is only intended to work with InOrder"); } } diff --git a/src/test/java/org/mockitoutil/ClassLoadersTest.java b/src/test/java/org/mockitoutil/ClassLoadersTest.java index baecd02dfb..59da6e5bdd 100644 --- a/src/test/java/org/mockitoutil/ClassLoadersTest.java +++ b/src/test/java/org/mockitoutil/ClassLoadersTest.java @@ -5,6 +5,7 @@ package org.mockitoutil; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.junit.Assert.fail; import static org.mockitoutil.ClassLoaders.currentClassLoader; import static org.mockitoutil.ClassLoaders.excludingClassLoader; @@ -23,20 +24,22 @@ public class ClassLoadersTest { "org.mockitoutil.ClassLoadersTest$ClassUsingInterface1"; public static final String INTERFACE_NAME = "org.mockitoutil.ClassLoadersTest$Interface1"; - @Test(expected = ClassNotFoundException.class) - public void isolated_class_loader_cannot_load_classes_when_no_given_prefix() throws Exception { + @Test + public void isolated_class_loader_cannot_load_classes_when_no_given_prefix() { // given ClassLoader cl = isolatedClassLoader().build(); - // when - cl.loadClass("org.mockito.Mockito"); - - // then raises CNFE + // when / then + assertThatThrownBy( + () -> { + cl.loadClass("org.mockito.Mockito"); + }) + .isInstanceOf(ClassNotFoundException.class) + .hasMessage("Can only load classes with prefixes : [], but not : []"); } @Test - public void isolated_class_loader_cannot_load_classes_if_no_code_source_path() - throws Exception { + public void isolated_class_loader_cannot_load_classes_if_no_code_source_path() { // given ClassLoader cl = isolatedClassLoader().withPrivateCopyOf(CLASS_NAME_DEPENDING_ON_INTERFACE).build(); @@ -113,7 +116,7 @@ public void isolated_class_loader_can_load_classes_isolated_classes_in_isolation } @Test - public void isolated_class_loader_cannot_load_classes_if_prefix_excluded() throws Exception { + public void isolated_class_loader_cannot_load_classes_if_prefix_excluded() { // given ClassLoader cl = isolatedClassLoader() @@ -135,7 +138,7 @@ public void isolated_class_loader_cannot_load_classes_if_prefix_excluded() throw } @Test - public void isolated_class_loader_has_no_parent() throws Exception { + public void isolated_class_loader_has_no_parent() { ClassLoader cl = isolatedClassLoader() .withCurrentCodeSourceUrls() @@ -146,16 +149,18 @@ public void isolated_class_loader_has_no_parent() throws Exception { assertThat(cl.getParent()).isNull(); } - @Test(expected = ClassNotFoundException.class) - public void excluding_class_loader_cannot_load_classes_when_no_correct_source_url_set() - throws Exception { + @Test + public void excluding_class_loader_cannot_load_classes_when_no_correct_source_url_set() { // given ClassLoader cl = excludingClassLoader().withCodeSourceUrlOf(this.getClass()).build(); - // when - cl.loadClass("org.mockito.Mockito"); - - // then class CNFE + // when / then + assertThatThrownBy( + () -> { + cl.loadClass("org.mockito.Mockito"); + }) + .isInstanceOf(ClassNotFoundException.class) + .hasMessage("org.mockito.Mockito"); } @Test @@ -194,7 +199,7 @@ public void excluding_class_loader_cannot_load_class_when_excluded_prefix_match_ } @Test - public void can_not_load_a_class_not_previously_registered_in_builder() throws Exception { + public void can_not_load_a_class_not_previously_registered_in_builder() { // given ClassLoader cl = ClassLoaders.inMemoryClassLoader() @@ -266,7 +271,7 @@ public void can_list_all_classes_reachable_in_a_classloader() throws Exception { } @Test - public void return_bootstrap_classloader() throws Exception { + public void return_bootstrap_classloader() { assertThat(jdkClassLoader()).isNotEqualTo(Mockito.class.getClassLoader()); assertThat(jdkClassLoader()).isNotEqualTo(ClassLoaders.class.getClassLoader()); assertThat(jdkClassLoader()).isEqualTo(Number.class.getClassLoader()); @@ -274,7 +279,7 @@ public void return_bootstrap_classloader() throws Exception { } @Test - public void return_current_classloader() throws Exception { + public void return_current_classloader() { assertThat(currentClassLoader()).isEqualTo(this.getClass().getClassLoader()); } diff --git a/src/test/java/org/mockitoutil/SafeJUnitRuleTest.java b/src/test/java/org/mockitoutil/SafeJUnitRuleTest.java index 3ac6397c2b..cfc4dd1c4a 100644 --- a/src/test/java/org/mockitoutil/SafeJUnitRuleTest.java +++ b/src/test/java/org/mockitoutil/SafeJUnitRuleTest.java @@ -4,7 +4,10 @@ */ package org.mockitoutil; -import static org.junit.Assert.*; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; import static org.mockito.Mockito.mock; import org.assertj.core.api.Assertions; @@ -23,7 +26,7 @@ public void happy_path_no_exception() throws Throwable { // when rule.apply( new Statement() { - public void evaluate() throws Throwable { + public void evaluate() { // all good } }, @@ -35,18 +38,23 @@ public void evaluate() throws Throwable { assertTrue(delegate.statementEvaluated); } - @Test(expected = IllegalArgumentException.class) - public void regular_failing_test() throws Throwable { - // when - rule.apply( - new Statement() { - public void evaluate() throws Throwable { - throw new IllegalArgumentException(); - } - }, - mock(FrameworkMethod.class), - this) - .evaluate(); + @Test + public void regular_failing_test() { + // given + Statement baseStatement = + new Statement() { + public void evaluate() { + throw new IllegalArgumentException(); + } + }; + Statement statement = rule.apply(baseStatement, mock(FrameworkMethod.class), this); + + // when / then + assertThatThrownBy( + () -> { + statement.evaluate(); + }) + .isInstanceOf(IllegalArgumentException.class); } @Test @@ -57,7 +65,7 @@ public void rule_threw_exception() throws Throwable { // when rule.apply( new Statement() { - public void evaluate() throws Throwable { + public void evaluate() { throw new AssertionError("x"); } }, @@ -75,7 +83,7 @@ public void expected_exception_but_no_exception() throws Throwable { try { rule.apply( new Statement() { - public void evaluate() throws Throwable { + public void evaluate() { // all good } }, @@ -99,7 +107,7 @@ public void expected_exception_message_did_not_match() throws Throwable { try { rule.apply( new Statement() { - public void evaluate() throws Throwable { + public void evaluate() { throw new AssertionError("BAR"); } }, @@ -121,7 +129,7 @@ public void expected_exception_type_did_not_match() throws Throwable { try { rule.apply( new Statement() { - public void evaluate() throws Throwable { + public void evaluate() { throw new RuntimeException("x"); } }, @@ -148,7 +156,7 @@ public void doAssert(Throwable t) { try { rule.apply( new Statement() { - public void evaluate() throws Throwable { + public void evaluate() { throw new RuntimeException(); } }, diff --git a/subprojects/inline/src/test/java/org/mockitoinline/ConstructionMockTest.java b/subprojects/inline/src/test/java/org/mockitoinline/ConstructionMockTest.java index dd5e46d494..4195080814 100644 --- a/subprojects/inline/src/test/java/org/mockitoinline/ConstructionMockTest.java +++ b/subprojects/inline/src/test/java/org/mockitoinline/ConstructionMockTest.java @@ -4,6 +4,14 @@ */ package org.mockitoinline; +import static junit.framework.TestCase.assertEquals; +import static junit.framework.TestCase.assertNull; +import static junit.framework.TestCase.assertTrue; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + import java.util.Collections; import java.util.concurrent.atomic.AtomicReference; @@ -12,9 +20,6 @@ import org.mockito.Mockito; import org.mockito.exceptions.base.MockitoException; -import static junit.framework.TestCase.*; -import static org.mockito.Mockito.*; - public final class ConstructionMockTest { @Test @@ -113,19 +118,27 @@ public void testConstructionMockCanCoexistWithMockInDifferentThread() throws Int } } - @Test(expected = MockitoException.class) + @Test public void testConstructionMockMustBeExclusiveInScopeWithinThread() { - try ( - MockedConstruction dummy = Mockito.mockConstruction(Dummy.class); - MockedConstruction duplicate = Mockito.mockConstruction(Dummy.class) - ) { - fail("Not supposed to allow duplicates"); - } + assertThatThrownBy( + () -> { + try ( + MockedConstruction dummy = Mockito.mockConstruction(Dummy.class); + MockedConstruction duplicate = Mockito.mockConstruction(Dummy.class)) { + } + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("static mocking is already registered in the current thread"); } - @Test(expected = MockitoException.class) + @Test public void testConstructionMockMustNotTargetAbstractClass() { - Mockito.mockConstruction(Runnable.class).close(); + assertThatThrownBy( + () -> { + Mockito.mockConstruction(Runnable.class).close(); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("It is not possible to construct primitive types or abstract types"); } static class Dummy { diff --git a/subprojects/inline/src/test/java/org/mockitoinline/StaticMockTest.java b/subprojects/inline/src/test/java/org/mockitoinline/StaticMockTest.java index c0fb1cbc29..eaa3ed1970 100644 --- a/subprojects/inline/src/test/java/org/mockitoinline/StaticMockTest.java +++ b/subprojects/inline/src/test/java/org/mockitoinline/StaticMockTest.java @@ -6,14 +6,12 @@ import static junit.framework.TestCase.assertEquals; import static junit.framework.TestCase.assertNull; -import static junit.framework.TestCase.fail; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.times; import java.util.concurrent.atomic.AtomicReference; -import org.assertj.core.api.ThrowableAssert; import org.junit.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; @@ -41,10 +39,15 @@ public void testStaticMockWithVerification() { } } - @Test(expected = WantedButNotInvoked.class) + @Test public void testStaticMockWithVerificationFailed() { try (MockedStatic dummy = Mockito.mockStatic(Dummy.class)) { - dummy.verify(Dummy::foo); + assertThatThrownBy( + () -> { + dummy.verify(Dummy::foo); + }) + .isInstanceOf(WantedButNotInvoked.class) + .hasMessageContaining("there were zero interactions with this mock"); } } @@ -56,12 +59,18 @@ public void testStaticMockWithNoInteractions() { } } - @Test(expected = NoInteractionsWanted.class) + @Test public void testStaticMockWithNoInteractionsFailed() { try (MockedStatic dummy = Mockito.mockStatic(Dummy.class)) { dummy.when(Dummy::foo).thenReturn("bar"); assertEquals("bar", Dummy.foo()); - dummy.verifyNoInteractions(); + assertThatThrownBy( + () -> { + dummy.verifyNoInteractions(); + }) + .isInstanceOf(NoInteractionsWanted.class) + .hasMessageContaining("No interactions wanted here") + .hasMessageContaining("above is the only interaction with this mock."); } } @@ -75,12 +84,18 @@ public void testStaticMockWithNoMoreInteractions() { } } - @Test(expected = NoInteractionsWanted.class) + @Test public void testStaticMockWithNoMoreInteractionsFailed() { try (MockedStatic dummy = Mockito.mockStatic(Dummy.class)) { dummy.when(Dummy::foo).thenReturn("bar"); assertEquals("bar", Dummy.foo()); - dummy.verifyNoMoreInteractions(); + assertThatThrownBy( + () -> { + dummy.verifyNoInteractions(); + }) + .isInstanceOf(NoInteractionsWanted.class) + .hasMessageContaining("No interactions wanted here") + .hasMessageContaining("above is the only interaction with this mock."); } } @@ -159,14 +174,18 @@ public void testStaticMockCanCoexistWithMockInDifferentThread() throws Interrupt } } - @Test(expected = MockitoException.class) + @Test public void testStaticMockMustBeExclusiveInScopeWithinThread() { - try ( - MockedStatic dummy = Mockito.mockStatic(Dummy.class); - MockedStatic duplicate = Mockito.mockStatic(Dummy.class) - ) { - fail("Not supposed to allow duplicates"); - } + assertThatThrownBy( + () -> { + try ( + MockedStatic dummy = Mockito.mockStatic(Dummy.class); + MockedStatic duplicate = Mockito.mockStatic(Dummy.class) + ) { + } + }) + .isInstanceOf(MockitoException.class) + .hasMessageContaining("static mocking is already registered in the current thread"); } @Test @@ -184,11 +203,9 @@ public void testStaticMockVoid() { public void testStaticMockMustUseValidMatchers() { try (MockedStatic mockedClass = Mockito.mockStatic(Dummy.class)) { assertThatThrownBy( - new ThrowableAssert.ThrowingCallable() { - public void call() { + () -> { mockedClass.when(() -> Dummy.fooVoid("foo", any())).thenReturn(null); - } - }) + }) .hasMessageContaining("Invalid use of argument matchers!"); Dummy.fooVoid("foo", "bar"); diff --git a/subprojects/proxy/proxy.gradle b/subprojects/proxy/proxy.gradle index e96f51b9a2..1ba13b5527 100644 --- a/subprojects/proxy/proxy.gradle +++ b/subprojects/proxy/proxy.gradle @@ -5,6 +5,7 @@ apply from: "$rootDir/gradle/java-library.gradle" dependencies { implementation project.rootProject testImplementation libraries.junit4 + testImplementation libraries.assertj } tasks.javadoc.enabled = false diff --git a/subprojects/proxy/src/test/java/org/mockitoproxy/MocksTest.java b/subprojects/proxy/src/test/java/org/mockitoproxy/MocksTest.java index 81e55f4817..7bea67814c 100644 --- a/subprojects/proxy/src/test/java/org/mockitoproxy/MocksTest.java +++ b/subprojects/proxy/src/test/java/org/mockitoproxy/MocksTest.java @@ -4,16 +4,7 @@ */ package org.mockitoproxy; -import org.hamcrest.CoreMatchers; -import org.junit.Test; -import org.mockito.Mockito; -import org.mockito.exceptions.base.MockitoException; - -import java.io.ByteArrayOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.lang.reflect.Proxy; - +import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.hamcrest.CoreMatchers.instanceOf; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -21,6 +12,16 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.lang.reflect.Proxy; + +import org.hamcrest.CoreMatchers; +import org.junit.Test; +import org.mockito.Mockito; +import org.mockito.exceptions.base.MockitoException; + public class MocksTest { @Test @@ -103,9 +104,17 @@ public Class findClass(String name) throws ClassNotFoundException { assertThat(mock.toString(), is("value")); } - @Test(expected = MockitoException.class) + @Test public void cannot_create_mock_of_non_object_class() { - Number number = Mockito.mock(Number.class); + assertThatThrownBy( + () -> { + Number number = Mockito.mock(Number.class); + }) + .isInstanceOf(MockitoException.class) + .hasMessageContainingAll( + "Cannot mock/spy class", + "Mockito cannot mock/spy because :", + " - non-interface"); } public interface SomeInterface {