@Test public void subscribeOnlyOnceFlowableOperatorErrorsWhenMultipleSubscribe() { SubscribeOnlyOnceFlowableOperator<Object> op = new SubscribeOnlyOnceFlowableOperator<Object>(); Subscriber<Object> innerSub = mock(Subscriber.class); final Subscription subscription = mock(Subscription.class); final Subscriber<Object> outerSub = op.apply(innerSub); outerSub.onSubscribe(subscription); assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { @Override public void call() { outerSub.onSubscribe(subscription); } }) .isInstanceOf(NullPointerException.class) .hasMessageContaining("cannot directly subscribe to a gRPC service multiple times"); verify(innerSub, times(1)).onSubscribe(subscription); }
@Test public void subscribeOnlyOnceSingleOperatorErrorsWhenMultipleSubscribe() { SubscribeOnlyOnceSingleOperator<Object> op = new SubscribeOnlyOnceSingleOperator<Object>(); SingleObserver<Object> innerSub = mock(SingleObserver.class); final Disposable disposable = mock(Disposable.class); final SingleObserver<Object> outerSub = op.apply(innerSub); outerSub.onSubscribe(disposable); assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { @Override public void call() { outerSub.onSubscribe(disposable); } }) .isInstanceOf(NullPointerException.class) .hasMessageContaining("cannot directly subscribe to a gRPC service multiple times"); verify(innerSub, times(1)).onSubscribe(disposable); }
@Test public void testExecutingTwiceThrowsIllegalStateException() throws Exception { Request request = RequestUtils.getUserInfoRequest(Endpoint.DEFAULT); mockConnection(createDummyConnection(request.endpoint(), MOCK_EMPTY_ARRAY_RESPONSE)); final RealCall call = getMockRealCall(request, executor); call.execute(); assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { call.execute(); } }).isInstanceOf(IllegalStateException.class); }
@Test public void testEnqueueWithTimeoutBlocksUntilTimeout() throws Exception { Request request = RequestUtils.getUserInfoRequest(Endpoint.DEFAULT); final Connection connection = createDummyConnection(Endpoint.DEFAULT, MOCK_EMPTY_ARRAY_RESPONSE); mockConnection(connection); final RealCall call = getMockRealCall(request, realExecutor); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { Thread.sleep(MOCK_TIMEOUT_TIME); return connection.sink(); } }).when(connection).sink(); assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { call.enqueueAndWait(MOCK_TIMEOUT_TIME, TimeUnit.MILLISECONDS); } }).isInstanceOf(TimeoutException.class); }
@Test public void testExecutingTwiceThrowsIllegalStateException() throws Exception { Connection connection = createDummyConnection(Endpoint.DEFAULT, getMockByteDataResponse(1)); retrofitConnectionProvider(connection); final MultiCall multiCall = createMultiCall(connection, executor); multiCall.execute(); assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { multiCall.execute(); } }).isInstanceOf(IllegalStateException.class); }
@Test public void testExecutingAfterCancelThrowsIOException() throws Exception { Connection connection = createDummyConnection(Endpoint.DEFAULT, getMockByteDataResponse(1)); retrofitConnectionProvider(connection); final MultiCall multiCall = createMultiCall(connection, executor); multiCall.cancel(); assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { multiCall.execute(); } }).isInstanceOf(IOException.class); }
@Test public void testEnqueueWithTimeoutBlocksUntilTimeout() throws Exception { final Connection connection = createDummyConnection(Endpoint.DEFAULT, getMockByteDataResponse(1)); retrofitConnectionProvider(connection); final MultiCall multiCall = createMultiCall(connection, realExecutor); doAnswer(new Answer() { @Override public Object answer(InvocationOnMock invocation) throws Throwable { Thread.sleep(MOCK_TIMEOUT_TIME); return connection.sink(); } }).when(connection).sink(); assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { multiCall.enqueueAndWait(MOCK_TIMEOUT_TIME, TimeUnit.MILLISECONDS); } }).isInstanceOf(TimeoutException.class); }
@Test public void fromBytes_withNullIntent_throwsBadParcelableException() { final byte[] intentBytes = toBytesUnchecked(null); assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { IntentUtil.fromBytes(intentBytes); } }).isInstanceOf(BadParcelableException.class); }
@Test public void rollbackToPosition() throws Exception { // Populate a session state with dummy data for a single partition final SessionState sessionState = new SessionState(); PartitionState partitionState = new PartitionState(); partitionState.addToFailoverLog(5, 12345); partitionState.setStartSeqno(1); partitionState.setEndSeqno(1000); partitionState.setSnapshotStartSeqno(2); partitionState.setSnapshotEndSeqno(3); sessionState.set(0, partitionState); Throwable th = catchThrowable(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { sessionState.rollbackToPosition((short) 0, 1L); } }); assertThat(th).isNull(); }
private void verifyMetadata(final DefaultErrorDTO error, MetadataArgOption metadataArgOption, Map<String, Object> expectedMetadata) { switch(metadataArgOption) { case NULL: case EMPTY: // intentional fall-through assertThat(error.metadata) .isNotNull() .isEmpty(); break; case NOT_EMPTY: assertThat(error.metadata) .isNotSameAs(expectedMetadata) .isEqualTo(expectedMetadata); Throwable ex = catchThrowable(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { error.metadata.put("can't modify", "me"); } }); assertThat(ex).isInstanceOf(UnsupportedOperationException.class); break; default: throw new IllegalArgumentException("Unhandled case: " + metadataArgOption); } }
@Test public void findRandomApiErrorWithHttpStatusCode_throws_IllegalStateException_if_it_cannot_find_error_with_specified_status_code() { // given final ProjectApiErrorsTestBase base = new ProjectApiErrorsTestBase() { @Override protected ProjectApiErrors getProjectApiErrors() { return ProjectApiErrorsForTesting.withProjectSpecificData(null, null); } }; // when Throwable ex = catchThrowable(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { base.findRandomApiErrorWithHttpStatusCode(42424242); } }); // then assertThat(ex).isInstanceOf(IllegalStateException.class); }
@Test public void verifyGetStatusCodePriorityOrderMethodContainsAllRelevantCodes_throws_AssertionError_if_it_finds_bad_state() { // given final ProjectApiErrorsTestBase base = new ProjectApiErrorsTestBase() { @Override protected ProjectApiErrors getProjectApiErrors() { return ProjectApiErrorsForTesting.withProjectSpecificData(Arrays.<ApiError>asList( new ApiErrorBase("FOOBAR", 42, "foo", 123456) ), ProjectSpecificErrorCodeRange.ALLOW_ALL_ERROR_CODES); } }; // when Throwable ex = catchThrowable(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { base.verifyGetStatusCodePriorityOrderMethodContainsAllRelevantCodes(); } }); // then assertThat(ex) .isInstanceOf(AssertionError.class) .hasMessageContaining("getStatusCodePriorityOrder() did not contain HTTP Status Code: 123456"); }
@Test public void getOwnerClass_throws_IllegalArgumentException_if_AnnotatedElement_is_not_Member_or_Class() { // given final AnnotatedElement notMemberOrClass = mock(AnnotatedElement.class); // when Throwable ex = catchThrowable(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { ReflectionBasedJsr303AnnotationTrollerBase.getOwnerClass(notMemberOrClass); } }); // then assertThat(ex).isInstanceOf(IllegalArgumentException.class); }
@Test public void extractMessageFromAnnotation_throws_wrapped_RuntimeException_if_annotation_blows_up() { // given RuntimeException exToThrow = new RuntimeException("kaboom"); final Annotation annotation = mock(Annotation.class); doThrow(exToThrow).when(annotation).annotationType(); // when Throwable actual = catchThrowable(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { ReflectionBasedJsr303AnnotationTrollerBase.extractMessageFromAnnotation(annotation); } }); // then assertThat(actual) .isNotEqualTo(exToThrow) .isInstanceOf(RuntimeException.class) .hasCause(exToThrow); }
@Test public void MetadataPropertyWriter_serializeAsField_still_works_for_non_Error_objects() throws Exception { // given final MetadataPropertyWriter mpw = new MetadataPropertyWriter(mock(BeanPropertyWriter.class)); // when Throwable ex = catchThrowable(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { mpw.serializeAsField(new Object(), mock(JsonGenerator.class), mock(SerializerProvider.class)); } }); // then // We expect a NPE because mocking a base BeanPropertyWriter is incredibly difficult and not worth the effort. assertThat(ex).isInstanceOf(NullPointerException.class); }
@Test public void SmartErrorCodePropertyWriter_serializeAsField_still_works_for_non_Error_objects() throws Exception { // given final SmartErrorCodePropertyWriter secpw = new SmartErrorCodePropertyWriter(mock(BeanPropertyWriter.class)); // when Throwable ex = catchThrowable(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { secpw.serializeAsField(new Object(), mock(JsonGenerator.class), mock(SerializerProvider.class)); } }); // then // We expect a NPE because mocking a base BeanPropertyWriter is incredibly difficult and not worth the effort. assertThat(ex).isInstanceOf(NullPointerException.class); }
@Test public void sendSpans_with_span_list_does_not_propagate_IOException_error_thrown_by_sendSpans_with_byte_array() throws IOException { // given doThrow(new IOException("kaboom")).when(implSpy).sendSpans(any(byte[].class)); // when Throwable ex = catchThrowable(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { implSpy.sendSpans(Collections.singletonList(zipkinSpan(42, "foo"))); } }); // then verify(implSpy).sendSpans(any(byte[].class)); assertThat(ex).isNull(); }
@Test public void sendSpans_with_span_list_propagates_RuntimeExceptions_thrown_by_sendSpans_with_byte_array() throws IOException { // given RuntimeException runtimeException = new RuntimeException("kaboom"); doThrow(runtimeException).when(implSpy).sendSpans(any(byte[].class)); // when Throwable ex = catchThrowable(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { implSpy.sendSpans(Collections.singletonList(zipkinSpan(42, "foo"))); } }); // then verify(implSpy).sendSpans(any(byte[].class)); assertThat(ex).isSameAs(runtimeException); }
@Test public void ZipkinSpanSenderJob_does_not_propagate_any_errors() { // given ZipkinSpanSenderDefaultHttpImpl senderImplMock = mock(ZipkinSpanSenderDefaultHttpImpl.class); BlockingQueue<zipkin.Span> spanBlockingQueueMock = mock(BlockingQueue.class); doThrow(new RuntimeException("kaboom")).when(spanBlockingQueueMock).isEmpty(); final ZipkinSpanSenderDefaultHttpImpl.ZipkinSpanSenderJob senderJob = new ZipkinSpanSenderDefaultHttpImpl.ZipkinSpanSenderJob(senderImplMock, spanBlockingQueueMock); // when Throwable propagatedEx = catchThrowable(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { senderJob.run(); } }); // then verify(spanBlockingQueueMock).isEmpty(); assertThat(propagatedEx).isNull(); verify(spanBlockingQueueMock, never()).drainTo(any(Collection.class)); verifyZeroInteractions(senderImplMock); }
@Test public void sendSpans_does_not_propagate_5xx_errors() throws Exception { // given zipkinRule.enqueueFailure(HttpFailure.sendErrorResponse(500, "Server Error!")); // when Throwable ex = catchThrowable(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { implSpy.sendSpans(Collections.singletonList(zipkinSpan(42, "foo"))); } }); // then assertThat(ex).isNull(); }
@Test public void sendSpans_does_not_propagate_connection_errors() throws Exception { // given zipkinRule.enqueueFailure(HttpFailure.disconnectDuringBody()); // when Throwable ex = catchThrowable(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { implSpy.sendSpans(Collections.singletonList(zipkinSpan(42, "foo"))); } }); // then assertThat(ex).isNull(); }
@Test public void spanCompleted_does_not_propagate_exceptions_generated_by_span_converter() { // given doThrow(new RuntimeException("kaboom")).when(spanConverterMock).convertWingtipsSpanToZipkinSpan(any(Span.class), any(Endpoint.class), any(String.class)); // when Throwable ex = catchThrowable(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { listener.spanCompleted(spanMock); } }); // then verify(spanConverterMock).convertWingtipsSpanToZipkinSpan(spanMock, listener.zipkinEndpoint, localComponentNamespace); verifyZeroInteractions(spanSenderMock); assertThat(ex).isNull(); }
@Test public void spanCompleted_does_not_propagate_exceptions_generated_by_span_sender() { // given doThrow(new RuntimeException("kaboom")).when(spanSenderMock).handleSpan(any(zipkin.Span.class)); // when Throwable ex = catchThrowable(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { listener.spanCompleted(spanMock); } }); // then verify(spanSenderMock).handleSpan(any(zipkin.Span.class)); assertThat(ex).isNull(); }
@Test public void configureKafkaMetrics_withNullMap_NullPointerException() { assertThatExceptionOfType(NullPointerException.class) .isThrownBy(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { KafkaConfigUtils.configureKafkaMetrics(null, mockGaugeService()); } }); final ScheduledExecutorService executors = Executors.newSingleThreadScheduledExecutor(); try { assertThatExceptionOfType(NullPointerException.class) .isThrownBy(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { KafkaConfigUtils.configureKafkaMetrics(null, mockGaugeService(), "test", executors, 10L); } }); } finally { executors.shutdown(); } }
@Test public void configureKafkaMetrics_withNullGaugeService_NullPointerException() { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { KafkaConfigUtils.configureKafkaMetrics(new HashMap<String, Object>(), null); } }) .withMessageContaining("Initializing GaugeService as null is meaningless!"); final ScheduledExecutorService executors = Executors.newSingleThreadScheduledExecutor(); try { assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { KafkaConfigUtils.configureKafkaMetrics(new HashMap<String, Object>(), null, "test", executors, 10L); } }) .withMessageContaining("Initializing GaugeService as null is meaningless!"); } finally { executors.shutdown(); } }
@Test public void shouldKeepDescriptionInErrorMessage() { //given final String DESCRIPTION = "minimum range closer than 100"; //when ts.findNumberOfShipsInRangeByCriteria(searchCriteria); //then ThrowableAssert.ThrowingCallable verifyLambda = () -> { verify(ts).findNumberOfShipsInRangeByCriteria(argLambda(c -> c.getMinimumRange() < 100, DESCRIPTION)); }; assertThatThrownBy(verifyLambda) .isInstanceOf(AssertionError.class) .hasMessageContaining("Argument(s) are different! Wanted:\n" + "ts.findNumberOfShipsInRangeByCriteria(\n" + " " + DESCRIPTION + "\n" + ");") .hasMessageContaining("Actual invocation has different arguments:\n" + "ts.findNumberOfShipsInRangeByCriteria(\n" + " ShipSearchCriteria{minimumRange=1000, numberOfPhasers=4}\n" + ");"); }
@Test public void shouldHaveMeaningfulErrorMessage() { //when ts.findNumberOfShipsInRangeByCriteria(searchCriteria); //then ThrowableAssert.ThrowingCallable verifyLambda = () -> { verify(ts).findNumberOfShipsInRangeByCriteria(assertArg(sc -> assertThat(sc.getMinimumRange()).isLessThan(50))); }; assertThatThrownBy(verifyLambda) .isInstanceOf(AssertionError.class) .hasMessageContaining("Argument(s) are different! Wanted:\n" + "ts.findNumberOfShipsInRangeByCriteria(\n" + " AssertionMatcher reported: \n" + "Expecting:\n" + " <1000>\n" + "to be less than:\n" + " <50> ") .hasMessageContaining("Actual invocation has different arguments:\n" + "ts.findNumberOfShipsInRangeByCriteria(\n" + " ShipSearchCriteria{minimumRange=1000, numberOfPhasers=4}\n" + ");"); }
@Test public void testDuplicateBeanByBindingConfig() { assertThatThrownBy( new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { SpringApplication.run(TestBindingConfig.class); } }) .isInstanceOf(BeanDefinitionStoreException.class) .hasMessageContaining("bean definition with this name already exists") .hasMessageContaining(TestInvalidBinding.NAME) .hasNoCause(); }
@Test public void testExecutingAfterCancelThrowsIOException() throws Exception { Request request = RequestUtils.getUserInfoRequest(Endpoint.DEFAULT); mockConnection(createDummyConnection(request.endpoint(), MOCK_EMPTY_ARRAY_RESPONSE)); final RealCall call = getMockRealCall(request, executor); call.cancel(); assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { call.execute(); } }).isInstanceOf(IOException.class); }
@Test public void shouldFailOnInvalidSelectKeyword() { // given String query = "selectx * from cars"; // when ThrowableAssert.ThrowingCallable when = () -> sqlParser.parse(query); // then assertThatThrownBy(when).isInstanceOf(InvalidQueryException.class); }
@Test public void testBuilder_setAdditionalProperties_nullKey() { final Map<String, byte[]> mapWithNullKey = Maps.newHashMap(null, new byte[0]); assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { mBuilder.setAdditionalProperties(mapWithNullKey); } }).isInstanceOf(IllegalArgumentException.class); }
@Test public void testBuild_setAdditionalProperty_nullValue() { final Map<String, byte[]> mapWithNullValue = Maps.newHashMap("a", null); assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { mBuilder.setAdditionalProperties(mapWithNullValue); } }).isInstanceOf(IllegalArgumentException.class); }
@SuppressWarnings("ConstantConditions") @Test public void sendResponse_nullQuery_nullReponse() throws Exception { assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { mResponseSender.sendResponse(null, null); } }).isInstanceOf(NullPointerException.class); }
@Test public void userAgentAndIpAddressBothAreNullError() throws IOException { final String userAgent = null; final InetAddress ipAddress = null; assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { assertThat(emptyClient().check(userAgent, ipAddress)); } }).isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("userAgent") .hasMessageContaining("ipAddress "); }
@Test public void accurateAtIsNullError() throws IOException { final String userAgent = EMPTY; final InetAddress ipAddress = localHost; final Date accurateAt = null; assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { assertThat(emptyClient().checkAt(userAgent, ipAddress, accurateAt)); } }).isInstanceOf(IllegalArgumentException.class) .hasMessageContaining("accurateAt"); }
@Test public void noProviderInstalled() { assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { EmojiManager.getInstance().findEmoji("test"); } }).isInstanceOf(IllegalStateException.class).hasMessage("Please install an EmojiProvider through the EmojiManager.install() method first."); }
@Test public void installEmptyProvider() { assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { EmojiManager.install(TestEmojiProvider.emptyCategories()); } }).isInstanceOf(IllegalArgumentException.class).hasMessage("Your EmojiProvider must at least have one category with at least one emoji."); }
@Test public void installEmptyCategory() { assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { EmojiManager.install(TestEmojiProvider.emptyEmojis()); } }).isInstanceOf(IllegalArgumentException.class).hasMessage("Your EmojiProvider must at least have one category with at least one emoji."); }
@Test public void destroy() { EmojiManager.destroy(); assertThatThrownBy(new ThrowableAssert.ThrowingCallable() { @Override public void call() throws Throwable { EmojiManager.getInstance().findEmoji("test"); } }).isInstanceOf(IllegalStateException.class).hasMessage("Please install an EmojiProvider through the EmojiManager.install() method first."); }