Java 类org.assertj.core.api.ThrowableAssert.ThrowingCallable 实例源码

项目:powermock-examples-maven    文件:OnlyMockitoTest.java   
@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();

}
项目:java-samples    文件:AbstractServiceInterfaceTest.java   
@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();
}
项目:java-samples    文件:AbstractServiceInterfaceTest.java   
@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();
}
项目:java-samples    文件:QueryForObjectTest.java   
@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);
}
项目:java-samples    文件:UserServiceImplTest.java   
@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);

}
项目:java-samples    文件:UserServiceImplTest.java   
@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);

}
项目:java-samples    文件:UserServiceImplTest.java   
@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);

}
项目:java-samples    文件:ExceptionAutoWrapTest.java   
@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);
}
项目:java-samples    文件:ExceptionAutoWrapTest.java   
@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);
}
项目:java-samples    文件:ExceptionAutoWrapTest.java   
@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);
}
项目:java-samples    文件:ExceptionAutoWrapTest.java   
@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);
}
项目:java-samples    文件:MethodsThrowingExceptionsTest.java   
@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");
}
项目:centraldogma    文件:ExpectedExceptionAppender.java   
/**
 * 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());
    }
}
项目:dataenum    文件:OutputSpecFactoryTest.java   
@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");
}
项目:dataenum    文件:OutputSpecFactoryTest.java   
@Test
public void shouldThrowForNonClassName() throws Exception {
  assertThatThrownBy(
          new ThrowingCallable() {
            @Override
            public void call() throws Throwable {
              OutputSpecFactory.toOutputClass(TypeName.BOOLEAN);
            }
          })
      .isInstanceOf(ClassCastException.class);
}
项目:reactive-architectures-playground    文件:FactsAdapterTests.java   
@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);
}
项目:riposte    文件:HttpServletRequestWrapperForRequestInfoTest.java   
private void verifyUnsupportedOperation(ThrowingCallable operation) {
    // when
    Throwable ex = catchThrowable(operation);

    // then
    assertThat(ex).isInstanceOf(UnsupportedOperationException.class);
}
项目:riposte    文件:MediaRangeTest.java   
/**
 * 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);
}
项目:wingtips    文件:CallableWithTracingTest.java   
@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();
}
项目:wingtips    文件:RunnableWithTracingTest.java   
@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();
}
项目:wingtips    文件:TracingStateTest.java   
@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);
}
项目:powermock-examples-maven    文件:SkipGlobalIgnoreExampleTest.java   
@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");
}
项目:powermock-examples-maven    文件:GlobalIgnoreExampleTest.java   
@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();
}
项目:java-samples    文件:ServiceUtilisantUneInterfaceTest.java   
@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);
}
项目:java-samples    文件:StringBeanTest.java   
@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();
}
项目:java-samples    文件:IntegerBeanTest.java   
@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();
}
项目:java-samples    文件:BeanSimpleRepositoryInterfaceTest.java   
@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();
}
项目:java-samples    文件:UserServiceImpl_withoutAspects_IT.java   
@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);

}
项目:java-samples    文件:UserServiceImpl_withoutAspects_IT.java   
@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);
}
项目:java-samples    文件:UserServiceImpl_withoutAspects_IT.java   
@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);

}
项目:java-samples    文件:UserServiceImpl_withAspects_IT.java   
@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);

}
项目:java-samples    文件:UserServiceImpl_withAspects_IT.java   
@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);
}
项目:java-samples    文件:UserServiceImpl_withAspects_IT.java   
@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);

}
项目:java-samples    文件:MethodsThrowingExceptionsTest.java   
@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();
}
项目:aws-java-sdk    文件:AmazonS3FakeTest.java   
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);
}
项目:aws-java-sdk    文件:AmazonS3FakeTest.java   
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);
}
项目:random-beans    文件:CollectionRandomizersTest.java   
@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) };
}
项目:random-beans    文件:CollectionRandomizersTest.java   
@TestTemplate
@UseDataProvider("generateCollectionRandomizersWithIllegalSize")
public void specifiedSizeShouldBePositive(ThrowingCallable callable) {
    // when
    Throwable expectedException = catchThrowable(callable);

    // then
    assertThat(expectedException).isInstanceOf(IllegalArgumentException.class);
}
项目:assertj-core    文件:ThrowableAssert_built_with_then_method_Test.java   
@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");
 }
项目:assertj-core    文件:ThrowableAssert_built_with_then_method_Test.java   
@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");
 }