@Test public void should_mock_final_method() { final FinalClass finalClass = Mockito.mock(FinalClass.class); doNothing().when(finalClass).say(anyString()); Throwable throwable = catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { finalClass.say(RandomStringUtils.random(10)); } }); assertThat(throwable) .as("Final method is mocked and exception is not thrown") .isNull(); }
@Test public void validation_should_work_everytime_when_no_exception_is_thrown() { InterfaceAvecDesMethodes mock = mock(InterfaceAvecDesMethodes.class); when(mock.recuperationDesDonnees(anyString())).thenReturn(resultListMock()); final ServiceInterface service = getInterface(mock); Throwable thrownByMethod = catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { service.validationDonneesForId("0"); } }); assertThat(thrownByMethod).isNull(); }
@Test public void validation_should_work_everytime_when_sqlexception_is_thrown() throws SQLException { InterfaceAvecDesMethodes mock = mock(InterfaceAvecDesMethodes.class); when(mock.recuperationDesDonnees(anyString())).thenReturn(resultListMock()); doThrow(SQLException.class) .when(mock) .verificationDesDonnees(anyList()); final ServiceInterface service = getInterface(mock); Throwable thrownByMethod = catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { service.validationDonneesForId("0"); } }); assertThat(thrownByMethod).isNull(); }
@Test public void should_raise_and_exception_when_querying_for_unknow_object() { Throwable thrown = Assertions.catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { queryForObject.getIdForUser(4); failBecauseExceptionWasNotThrown(EmptyResultDataAccessException.class); } }); Assertions.assertThat(thrown) .isNotNull() .isInstanceOf(EmptyResultDataAccessException.class); }
@Test public void saveOrUpdate_should_raise_and_SQLException() { final UserService service = new UserServiceImpl(mock(UserDao.class)); Throwable throwable = Assertions.catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { service.saveOrUpdate(user(1l, "one")); } }); Assertions.assertThat(throwable) .isNotNull() .isInstanceOf(SQLException.class); }
@Test public void delete_should_raise_and_UnsupportedOperationException() { final UserService service = new UserServiceImpl(mock(UserDao.class)); Throwable throwable = Assertions.catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { service.delete(user(1l, "one")); } }); Assertions.assertThat(throwable) .isNotNull() .isInstanceOf(UnsupportedOperationException.class); }
@Test public void thisWillFailMiserabily_should_raise_and_UnsupportedOperationException() { final UserService service = new UserServiceImpl(mock(UserDao.class)); Throwable throwable = Assertions.catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { service.thisWillFailMiserabily(); } }); Assertions.assertThat(throwable) .isNotNull() .isInstanceOf(UnsupportedOperationException.class); }
@Test public void should_catch_any_exception_but_DomainException_and_wrap_it_into_DomainException() { final Exception thrown = new Exception(); assertThatThrownBy(new ThrowingCallable() { @Override public void call() throws Throwable { final ExceptionAutoWrap aspect = new ExceptionAutoWrap(); aspect.catchLogAndRethrow(thrown); failBecauseExceptionWasNotThrown(Exception.class); } }) .isNotNull() .isInstanceOf(DomainException.class) .hasCause(thrown); }
@Test public void should_catch_any_RuntimeException_and_wrap_it_into_DomainException() { final Exception thrown = new RuntimeException(); assertThatThrownBy(new ThrowingCallable() { @Override public void call() throws Throwable { final ExceptionAutoWrap aspect = new ExceptionAutoWrap(); aspect.catchLogAndRethrow(thrown); failBecauseExceptionWasNotThrown(Exception.class); } }) .isNotNull() .isInstanceOf(DomainException.class) .hasCause(thrown); }
@Test public void should_not_wrap_DomainException() { final Exception thrown = new DomainException("Test message"); assertThatThrownBy(new ThrowingCallable() { @Override public void call() throws Throwable { final ExceptionAutoWrap aspect = new ExceptionAutoWrap(); aspect.catchLogAndRethrow(thrown); failBecauseExceptionWasNotThrown(DomainException.class); } }) .isNotNull() .isInstanceOf(DomainException.class) .hasNoCause() .isEqualTo(thrown); }
@Test public void should_wrap_any_RuntimeException_into_Checked_Exception() { final RuntimeException thrown = new DomainException("Test message"); assertThatThrownBy(new ThrowingCallable() { @Override public void call() throws Throwable { final ExceptionAutoWrap aspect = new ExceptionAutoWrap(); aspect.wrapIntoNotRuntimeException(thrown); failBecauseExceptionWasNotThrown(Exception.class); } }) .isNotNull() .isInstanceOf(Exception.class) .hasCause(thrown); }
@Test public void should_raise_DiceException_when_rolling_dice_with_a_beautiful_test() { final MethodsThrowingExceptions method = new MethodsThrowingExceptions(21); // la meilleure façon de tester si on est en Java7 avec assertJ 2.X Throwable thrownByMethod = Assertions.catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { method.rollDice(); failBecauseExceptionWasNotThrown(DiceException.class); } }); assertThat(thrownByMethod) .isInstanceOf(RandomException.class) .isExactlyInstanceOf(DiceException.class) .hasMessageContaining("21 failures yet"); }
/** * Adds {@code "(expected exception)"} to the log message and lower its logging level to * {@link Level#DEBUG} if the exception occurred from the {@code shouldRaiseThrowable} matches * {@code throwable} and contains {@code message}. */ public static AbstractThrowableAssert<?, ? extends Throwable> assertThatThrownByWithExpectedException( Class<?> throwable, String message, ThrowingCallable shouldRaiseThrowable) throws Exception { requireNonNull(throwable, "throwable"); requireNonNull(message, "message"); requireNonNull(shouldRaiseThrowable, "shouldRaiseThrowable"); exceptionAndMessage.put(throwable.getName(), message); try { return assertThatThrownBy(shouldRaiseThrowable); } finally { exceptionAndMessage.remove(throwable.getName()); } }
@Test public void shouldThrowForNonDataenumClassName() throws Exception { assertThatThrownBy( new ThrowingCallable() { @Override public void call() throws Throwable { OutputSpecFactory.toOutputClass(ClassName.get("com.spotify", "My")); } }) .isInstanceOf(ParserException.class) .hasMessageContaining("Bad name"); }
@Test public void shouldThrowForNonClassName() throws Exception { assertThatThrownBy( new ThrowingCallable() { @Override public void call() throws Throwable { OutputSpecFactory.toOutputClass(TypeName.BOOLEAN); } }) .isInstanceOf(ClassCastException.class); }
@Test public void shouldCrash_WhenDataAvailable_ForViewTypes() { Activity host = buildActivity(FactsAboutNumbersActivity.class).create().get(); adapter = new FactsAdapter(LayoutInflater.from(host)); assertThat(adapter.getItemCount()).isEqualTo(0); ThrowingCallable call = () -> adapter.getItemViewType(0); assertThatThrownBy(call).isInstanceOf(IllegalStateException.class); }
private void verifyUnsupportedOperation(ThrowingCallable operation) { // when Throwable ex = catchThrowable(operation); // then assertThat(ex).isInstanceOf(UnsupportedOperationException.class); }
/** * MediaRange constructor should throw an IllegalArgumentException when the type, subtype, or qualityFactor properties are null. * Additionally, the constructor should throw an IllegalArgumentException when the quality factor value is less than 0 or greater than 1. */ @Test @UseDataProvider("nullMediaRangeConstructorTestSet") public void test_media_range_constructor_throws_exception_with_null_values (final String expectedErrorMessage, final ThrowingCallable callable) { // when Throwable ex = catchThrowable(callable); // then assertThat(ex) .isInstanceOf(IllegalArgumentException.class) .hasMessageStartingWith(expectedErrorMessage); }
@DataProvider(value = { "true", "false" }) @Test public void call_handles_tracing_and_mdc_info_as_expected(boolean throwException) throws Exception { // given throwExceptionDuringCall = throwException; Tracer.getInstance().startRequestWithRootSpan("foo"); Deque<Span> spanStack = Tracer.getInstance().getCurrentSpanStackCopy(); Map<String, String> mdcInfo = MDC.getCopyOfContextMap(); final CallableWithTracing instance = new CallableWithTracing( callableMock, spanStack, mdcInfo ); resetTracing(); assertThat(Tracer.getInstance().getCurrentSpanStackCopy()).isNull(); assertThat(MDC.getCopyOfContextMap()).isNullOrEmpty(); // when Throwable ex = catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { instance.call(); } }); // then verify(callableMock).call(); if (throwException) assertThat(ex).isNotNull(); else assertThat(ex).isNull(); assertThat(currentSpanStackWhenCallableWasCalled.get(0)).isEqualTo(spanStack); assertThat(currentMdcInfoWhenCallableWasCalled.get(0)).isEqualTo(mdcInfo); assertThat(Tracer.getInstance().getCurrentSpanStackCopy()).isNull(); assertThat(MDC.getCopyOfContextMap()).isNullOrEmpty(); }
@DataProvider(value = { "true", "false" }) @Test public void run_handles_tracing_and_mdc_info_as_expected(boolean throwException) { // given throwExceptionDuringCall = throwException; Tracer.getInstance().startRequestWithRootSpan("foo"); Deque<Span> spanStack = Tracer.getInstance().getCurrentSpanStackCopy(); Map<String, String> mdcInfo = MDC.getCopyOfContextMap(); final RunnableWithTracing instance = new RunnableWithTracing( runnableMock, spanStack, mdcInfo ); resetTracing(); assertThat(Tracer.getInstance().getCurrentSpanStackCopy()).isNull(); assertThat(MDC.getCopyOfContextMap()).isNullOrEmpty(); // when Throwable ex = catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { instance.run(); } }); // then verify(runnableMock).run(); if (throwException) assertThat(ex).isNotNull(); else assertThat(ex).isNull(); assertThat(currentSpanStackWhenRunnableWasCalled.get(0)).isEqualTo(spanStack); assertThat(currentMdcInfoWhenRunnableWasCalled.get(0)).isEqualTo(mdcInfo); assertThat(Tracer.getInstance().getCurrentSpanStackCopy()).isNull(); assertThat(MDC.getCopyOfContextMap()).isNullOrEmpty(); }
@Test public void setValue_throws_UnsupportedOperationException() { // when Throwable ex = catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { tracingState.setValue(mock(Map.class)); } }); // then assertThat(ex).isInstanceOf(UnsupportedOperationException.class); }
@Test public void should_not_throw_exception() { Throwable throwable = catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { new ClassLoadedDefaultClassLoader(); } }); assertThat(throwable) .as("Exception is not thrown") .isNotNull() .hasMessageContaining("system class loader"); }
@Test public void should_not_throw_exception() { Throwable throwable = catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { new ClassLoadedDefaultClassLoader(); } }); assertThat(throwable) .as("Exception is not thrown") .isNull(); }
@Test // meme test que precedemment, mais plus joli public void should_fail_when_getById_parameters_is_null2() { // ARRANGE // création d'un mock pour le repository BeanDeDomainRepository repository = mock(BeanDeDomainRepository.class); // Création du service avec le repository final ServiceUtilisantUneInterface service = new ServiceUtilisantUneInterface(repository); // ACT Throwable thrownByCall = Assertions.catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { service.getById(null); } }); // ASSERT assertThat(thrownByCall) .isNotNull() .isExactlyInstanceOf(NullPointerException.class) .hasMessageContaining("id parameter is mandatory"); // Le service ne doit pas avoir été appelé verifyZeroInteractions(repository); }
@Test public void should_not_raise_any_exception_when_saving_string() { final StringBean bean = new StringBean(); Throwable thrownByMethod = catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { bean.saveBean("DADA"); } }); assertThat(thrownByMethod).isNull(); }
@Test public void should_not_raise_any_exception_when_saving_integer() { final IntegerBean bean = new IntegerBean(); Throwable thrownByMethod = catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { bean.saveBean(Integer.valueOf(8)); } }); assertThat(thrownByMethod).isNull(); }
@Test public void should_save_bean_properly() { final BeanSimpleRepositoryInterface repo = getInterface(); final BeanSimple bean = new BeanSimple(Long.valueOf(1l), "one"); Throwable thrownByMethod = catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { repo.save(bean); } }); assertThat(thrownByMethod).isNull(); }
@Test public void saveOrUpdate_should_raise_an_SQLException_with_no_aspect() { Throwable throwable = Assertions.catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { userService.saveOrUpdate(user(1l, "one")); } }); assertThat(throwable) .isNotNull() .isInstanceOf(SQLException.class); }
@Test public void delete_should_raise_and_UnsupportedOperationException_with_no_aspect() { Throwable throwable = Assertions.catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { userService.delete(user(1l, "one")); } }); assertThat(throwable) .isNotNull() .isInstanceOf(UnsupportedOperationException.class); }
@Test public void thisWillFailMiserabily_should_raise_and_UnsupportedOperationException_with_no_aspect() { Throwable throwable = Assertions.catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { userService.thisWillFailMiserabily(); } }); assertThat(throwable) .isNotNull() .isInstanceOf(UnsupportedOperationException.class); }
@Test public void saveOrUpdate_should_raise_an_SQLException_but_aspect_should_throw_DomainException_instead() { Throwable throwable = Assertions.catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { userService.saveOrUpdate(user(1l, "one")); } }); assertThat(throwable) .isNotNull() .isInstanceOf(DomainException.class); }
@Test public void delete_should_raise_and_UnsupportedOperationException_but_aspect_should_throw_DomainException_instead() { Throwable throwable = Assertions.catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { userService.delete(user(1l, "one")); } }); assertThat(throwable) .isNotNull() .isInstanceOf(DomainException.class); }
@Test public void thisWillFailMiserabily_should_raise_and_UnsupportedOperationException_but_aspect_should_try_to_wrap_it_into_Exception() { Throwable throwable = Assertions.catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { userService.thisWillFailMiserabily(); } }); // exception thrown when not expected result in UndeclaredThrowableException assertThat(throwable) .isNotNull() .isInstanceOf(UndeclaredThrowableException.class); }
@Test public void should_not_raise_any_exception_when_passing_false() { final MethodsThrowingExceptions method = new MethodsThrowingExceptions(74); Throwable thrownByMethod = catchThrowable(new ThrowingCallable() { @Override public void call() throws Throwable { method.thisMethodMayFail(false); } }); assertThat(thrownByMethod).isNull(); }
protected void assertThatNoSuchBucketExists(ThrowingCallable shouldRaiseThrowable) { assertThatThrownBy(shouldRaiseThrowable) .hasRequestId() .hasErrorCode("NoSuchBucket") .hasErrorMessage("The specified bucket does not exist") .hasStatusCode(404) .hasExtendedRequestId() .containAdditionalDetail("BucketName", "missing_bucket") .containAdditionalDetailWithKey("Error") .hasServiceName("Amazon S3") .hasErrorType(Client); }
protected void assertThatAllAccessIsDisabled(ThrowingCallable shouldRaiseThrowable) { assertThatThrownBy(shouldRaiseThrowable) .hasRequestId() .hasErrorCode("AllAccessDisabled") .hasErrorMessage("All access to this object has been disabled") .hasStatusCode(403) .hasExtendedRequestId() .containAdditionalDetailWithKey("Error") .hasServiceName("Amazon S3") .hasErrorType(Client); }
@DataProvider public static Object[] generateCollectionRandomizersWithIllegalSize() { Randomizer<String> elementRandomizer = elementRandomizer(); int illegalSize = -1; return new Object[] { (ThrowingCallable) () -> aNewListRandomizer(elementRandomizer, illegalSize), (ThrowingCallable) () -> aNewQueueRandomizer(elementRandomizer, illegalSize), (ThrowingCallable) () -> aNewSetRandomizer(elementRandomizer, illegalSize) }; }
@TestTemplate @UseDataProvider("generateCollectionRandomizersWithIllegalSize") public void specifiedSizeShouldBePositive(ThrowingCallable callable) { // when Throwable expectedException = catchThrowable(callable); // then assertThat(expectedException).isInstanceOf(IllegalArgumentException.class); }
@Test public void should_build_ThrowableAssert_with_runtime_exception_thrown_by_callable_code() { // check that actual exception is the one thrown by Callable<Void>#run thenThrownBy(new ThrowingCallable() { @Override public void call() { throw new IllegalArgumentException("something was wrong"); } }).isInstanceOf(IllegalArgumentException.class).hasMessage("something was wrong"); }
@Test public void should_build_ThrowableAssert_with_throwable_thrown_by_callable_code() { thenThrownBy(new ThrowingCallable() { @Override public void call() throws Exception { throw new Exception("something was wrong"); } }).isInstanceOf(Exception.class).hasMessage("something was wrong"); }