org.assertj.core.api.ThrowableAssert Java Examples

The following examples show how to use org.assertj.core.api.ThrowableAssert. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ProjectApiErrorsTestBaseTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@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");
}
 
Example #2
Source File: ComponentsReporterTest.java    From litho with Apache License 2.0 6 votes vote down vote up
@Test
public void testEmitFatalMessage() {
  final Throwable throwable =
      catchThrowable(
          new ThrowableAssert.ThrowingCallable() {
            @Override
            public void call() throws Throwable {
              ComponentsReporter.emitMessage(FATAL, CATEGORY_KEY, FATAL_MSG);

              assertThat(mReporter.getLoggedMessages().size()).isEqualTo(1);
              assertThat(mReporter.getLoggedMessages()).contains(new Pair<>(FATAL, FATAL_MSG));
            }
          });
  assertThat(throwable).isInstanceOf(RuntimeException.class);
  assertThat(throwable.getMessage()).isEqualTo(FATAL_MSG);
}
 
Example #3
Source File: SubscribeOnlyOnceTest.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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);
}
 
Example #4
Source File: SubscribeOnlyOnceTest.java    From reactive-grpc with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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);
}
 
Example #5
Source File: AmqpClientActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void invalidSpecificOptionsThrowConnectionConfigurationInvalidException() {
    final Map<String, String> specificOptions = new HashMap<>();
    specificOptions.put("failover.unknown.option", "100");
    specificOptions.put("failover.nested.amqp.vhost", "ditto");
    final Connection connection = ConnectivityModelFactory.newConnectionBuilder(createRandomConnectionId(),
            ConnectionType.AMQP_10, ConnectivityStatus.OPEN, TestConstants.getUriOfNewMockServer())
            .specificConfig(specificOptions)
            .sources(singletonList(
                    ConnectivityModelFactory.newSourceBuilder()
                            .authorizationContext(Authorization.AUTHORIZATION_CONTEXT)
                            .address("source1")
                            .build()))
            .build();

    final ThrowableAssert.ThrowingCallable props1 =
            () -> AmqpClientActor.propsForTests(connection, ActorRef.noSender(), null, null);
    final ThrowableAssert.ThrowingCallable props2 =
            () -> AmqpClientActor.propsForTests(connection, ActorRef.noSender(), null, jmsConnectionFactory);

    Stream.of(props1, props2).forEach(throwingCallable ->
            assertThatExceptionOfType(ConnectionConfigurationInvalidException.class)
                    .isThrownBy(throwingCallable)
                    .withMessageContaining("unknown.option"));
}
 
Example #6
Source File: RabbitMQClientActorTest.java    From ditto with Eclipse Public License 2.0 6 votes vote down vote up
@Test
public void invalidTargetFormatThrowsConnectionConfigurationInvalidException() {
    final Connection connection = ConnectivityModelFactory.newConnectionBuilder(CONNECTION_ID,
            ConnectionType.AMQP_091, ConnectivityStatus.OPEN, TestConstants.getUriOfNewMockServer())
            .targets(Collections.singletonList(ConnectivityModelFactory.newTargetBuilder()
                    .address("exchangeOnly")
                    .authorizationContext(TestConstants.Authorization.AUTHORIZATION_CONTEXT)
                    .topics(Topic.TWIN_EVENTS)
                    .build()))
            .build();

    final ThrowableAssert.ThrowingCallable props1 =
            () -> RabbitMQClientActor.propsForTests(connection, Actor.noSender(), Actor.noSender(), null);
    final ThrowableAssert.ThrowingCallable props2 =
            () -> RabbitMQClientActor.propsForTests(connection, Actor.noSender(), Actor.noSender(),
                    rabbitConnectionFactoryFactory
            );
    Stream.of(props1, props2)
            .forEach(throwingCallable ->
                    assertThatExceptionOfType(ConnectionConfigurationInvalidException.class)
                            .isThrownBy(throwingCallable)
                            .withMessageContaining("exchangeOnly")
                            .withNoCause()
            );
}
 
Example #7
Source File: BesuPluginContextImplTest.java    From besu with Apache License 2.0 6 votes vote down vote up
@Test
public void lifecycleExceptions() throws Throwable {
  final BesuPluginContextImpl contextImpl = new BesuPluginContextImpl();
  final ThrowableAssert.ThrowingCallable registerPlugins =
      () -> contextImpl.registerPlugins(new File(".").toPath());

  assertThatExceptionOfType(IllegalStateException.class).isThrownBy(contextImpl::startPlugins);
  assertThatExceptionOfType(IllegalStateException.class).isThrownBy(contextImpl::stopPlugins);

  registerPlugins.call();
  assertThatExceptionOfType(IllegalStateException.class).isThrownBy(registerPlugins);
  assertThatExceptionOfType(IllegalStateException.class).isThrownBy(contextImpl::stopPlugins);

  contextImpl.startPlugins();
  assertThatExceptionOfType(IllegalStateException.class).isThrownBy(registerPlugins);
  assertThatExceptionOfType(IllegalStateException.class).isThrownBy(contextImpl::startPlugins);

  contextImpl.stopPlugins();
  assertThatExceptionOfType(IllegalStateException.class).isThrownBy(registerPlugins);
  assertThatExceptionOfType(IllegalStateException.class).isThrownBy(contextImpl::startPlugins);
  assertThatExceptionOfType(IllegalStateException.class).isThrownBy(contextImpl::stopPlugins);
}
 
Example #8
Source File: DefaultErrorDTOTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example #9
Source File: JavaPackageTest.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
@Test
public void test_getPackageInfo() {
    JavaPackage annotatedPackage = importPackage("packageexamples.annotated");
    final JavaPackage nonAnnotatedPackage = importPackage("packageexamples");

    assertThat(annotatedPackage.getPackageInfo()).isNotNull();

    assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
        @Override
        public void call() {
            nonAnnotatedPackage.getPackageInfo();
        }
    })
            .isInstanceOf(IllegalArgumentException.class)
            .hasMessageContaining(nonAnnotatedPackage.getDescription() + " does not contain a package-info.java");
}
 
Example #10
Source File: JsonUtilWithDefaultErrorContractDTOSupportTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #11
Source File: JavaPackageTest.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
@Test
public void test_getAnnotationOfType_type() {
    final JavaPackage annotatedPackage = importPackage("packageexamples.annotated");
    final JavaPackage nonAnnotatedPackage = importPackage("packageexamples");

    assertThat(annotatedPackage.getAnnotationOfType(PackageLevelAnnotation.class)).isInstanceOf(PackageLevelAnnotation.class);

    assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
        @Override
        public void call() {
            annotatedPackage.getAnnotationOfType(Deprecated.class);
        }
    }).isInstanceOf(IllegalArgumentException.class)
            .hasMessageContaining(annotatedPackage.getDescription() + " is not annotated with @" + Deprecated.class.getName());

    assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
        @Override
        public void call() {
            nonAnnotatedPackage.getAnnotationOfType(Deprecated.class);
        }
    }).isInstanceOf(IllegalArgumentException.class)
            .hasMessageContaining(nonAnnotatedPackage.getDescription() + " is not annotated with @" + Deprecated.class.getName());
}
 
Example #12
Source File: JavaPackageTest.java    From ArchUnit with Apache License 2.0 6 votes vote down vote up
@Test
public void test_getAnnotationOfType_typeName() {
    final JavaPackage annotatedPackage = importPackage("packageexamples.annotated");
    final JavaPackage nonAnnotatedPackage = importPackage("packageexamples");

    assertThat(annotatedPackage.getAnnotationOfType(PackageLevelAnnotation.class.getName())
            .getRawType()).matches(PackageLevelAnnotation.class);

    assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
        @Override
        public void call() {
            annotatedPackage.getAnnotationOfType("not.There");
        }
    }).isInstanceOf(IllegalArgumentException.class).hasMessageContaining(annotatedPackage.getDescription() + " is not annotated with @not.There");

    assertThatThrownBy(new ThrowableAssert.ThrowingCallable() {
        @Override
        public void call() {
            nonAnnotatedPackage.getAnnotationOfType("not.There");
        }
    }).isInstanceOf(IllegalArgumentException.class).hasMessageContaining(nonAnnotatedPackage.getDescription() + " is not annotated with @not.There");
}
 
Example #13
Source File: ProjectApiErrorsTestBaseTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #14
Source File: ReflectionBasedJsr303AnnotationTrollerBaseTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #15
Source File: ReflectionBasedJsr303AnnotationTrollerBaseTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #16
Source File: JsonUtilWithDefaultErrorContractDTOSupportTest.java    From backstopper with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #17
Source File: JaxRsWebApplicationExceptionHandlerListenerTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void constructor_throws_IllegalArgumentException_if_passed_null_projectApiErrors() {
    // when
    Throwable ex = Assertions.catchThrowable(new ThrowableAssert.ThrowingCallable() {
        @Override
        public void call() throws Throwable {
            new JaxRsWebApplicationExceptionHandlerListener(null, utils);
        }
    });

    // then
    assertThat(ex).isInstanceOf(IllegalArgumentException.class);
}
 
Example #18
Source File: ServersideValidationErrorHandlerListenerTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void constructor_throws_IllegalArgumentException_if_passed_null_utils() {
    // when
    Throwable ex = Assertions.catchThrowable(new ThrowableAssert.ThrowingCallable() {
        @Override
        public void call() throws Throwable {
            new ServersideValidationErrorHandlerListener(mock(ProjectApiErrors.class), null);
        }
    });

    // then
    Assertions.assertThat(ex).isInstanceOf(IllegalArgumentException.class);
}
 
Example #19
Source File: ServersideValidationErrorHandlerListenerTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void constructor_throws_IllegalArgumentException_if_passed_null_projectApiErrors() {
    // when
    Throwable ex = Assertions.catchThrowable(new ThrowableAssert.ThrowingCallable() {
        @Override
        public void call() throws Throwable {
            new ServersideValidationErrorHandlerListener(null, ApiExceptionHandlerUtils.DEFAULT_IMPL);
        }
    });

    // then
    Assertions.assertThat(ex).isInstanceOf(IllegalArgumentException.class);
}
 
Example #20
Source File: TraceAndSpanIdGeneratorTest.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@DataProvider(value = {
    "                                      ", // less than 16 chars
    "123e4567-e89b-12d3-a456-426655440000  ", // UUID format (hyphens and also >32 chars)
    "/                                     ", // before '0' char
    ":                                     ", // after '9' char
    "`                                     ", // before 'a' char
    "g                                     ", // after 'f' char
    "ABCDEF                                "  // uppercase hex chars
}, splitBy = "\\|")
@Test
public void unsignedLowerHexStringToLong_throws_NumberFormatException_for_illegal_args(final String badHexString) {
    // when selecting right-most 16 characters
    Throwable ex = catchThrowable(new ThrowableAssert.ThrowingCallable() {
        @Override
        public void call() throws Throwable {
            TraceAndSpanIdGenerator.unsignedLowerHexStringToLong(badHexString);
        }
    });

    // then
    assertThat(ex).isInstanceOf(NumberFormatException.class);

    // when selecting 16 characters at offset 0
    ex = catchThrowable(new ThrowableAssert.ThrowingCallable() {
        @Override
        public void call() throws Throwable {
            TraceAndSpanIdGenerator.unsignedLowerHexStringToLong(badHexString, 0);
        }
    });

    // then
    assertThat(ex).isInstanceOf(NumberFormatException.class);
}
 
Example #21
Source File: DownstreamNetworkExceptionHandlerListenerTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void constructor_throws_IllegalArgumentException_if_passed_null() {
    // when
    Throwable ex = Assertions.catchThrowable(new ThrowableAssert.ThrowingCallable() {
        @Override
        public void call() throws Throwable {
            new DownstreamNetworkExceptionHandlerListener(null);
        }
    });

    // then
    Assertions.assertThat(ex).isInstanceOf(IllegalArgumentException.class);
}
 
Example #22
Source File: ClientDataValidationErrorHandlerListenerTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void constructor_throws_IllegalArgumentException_if_passed_null_projectApiErrors() {
    // when
    Throwable ex = Assertions.catchThrowable(new ThrowableAssert.ThrowingCallable() {
        @Override
        public void call() throws Throwable {
            new ClientDataValidationErrorHandlerListener(null, ApiExceptionHandlerUtils.DEFAULT_IMPL);
        }
    });

    // then
    Assertions.assertThat(ex).isInstanceOf(IllegalArgumentException.class);
}
 
Example #23
Source File: IntegerRangeTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void constructor_throws_exception_if_upper_range_less_than_lower_range() {
    // when
    Throwable ex = catchThrowable(new ThrowableAssert.ThrowingCallable() {
        @Override
        public void call() throws Throwable {
            IntegerRange.of(5, 4);
        }
    });

    // then
    assertThat(ex).isInstanceOf(IllegalArgumentException.class);
}
 
Example #24
Source File: Jersey2WebApplicationExceptionHandlerListenerTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void constructor_throws_IllegalArgumentException_if_passed_null_projectApiErrors() {
    // when
    Throwable ex = Assertions.catchThrowable(new ThrowableAssert.ThrowingCallable() {
        @Override
        public void call() throws Throwable {
            new Jersey2WebApplicationExceptionHandlerListener(null, utils);
        }
    });

    // then
    assertThat(ex).isInstanceOf(IllegalArgumentException.class);
}
 
Example #25
Source File: Jersey2WebApplicationExceptionHandlerListenerTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void constructor_throws_IllegalArgumentException_if_passed_null_utils() {
    // when
    Throwable ex = Assertions.catchThrowable(new ThrowableAssert.ThrowingCallable() {
        @Override
        public void call() throws Throwable {
            new Jersey2WebApplicationExceptionHandlerListener(testProjectApiErrors, null);
        }
    });

    // then
    assertThat(ex).isInstanceOf(IllegalArgumentException.class);
}
 
Example #26
Source File: JaxRsApiExceptionHandlerTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void constructor_throws_IllegalArgumentException_if_jaxRsUnhandledExceptionHandler_is_null() {
    // when
    Throwable ex = catchThrowable(new ThrowableAssert.ThrowingCallable() {
        @Override
        public void call() throws Throwable {
            new JaxRsApiExceptionHandler(testProjectApiErrors, listenerList, ApiExceptionHandlerUtils.DEFAULT_IMPL, null);
        }
    });

    // then
    assertThat(ex).isInstanceOf(IllegalArgumentException.class);
}
 
Example #27
Source File: Jersey1ApiExceptionHandlerTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void constructor_throws_IllegalArgumentException_if_jerseyUnhandledExceptionHandler_is_null() {
    // when
    Throwable ex = catchThrowable(new ThrowableAssert.ThrowingCallable() {
        @Override
        public void call() throws Throwable {
            new Jersey1ApiExceptionHandler(testProjectApiErrors, listenerList, ApiExceptionHandlerUtils.DEFAULT_IMPL, null);
        }
    });

    // then
    assertThat(ex).isInstanceOf(IllegalArgumentException.class);
}
 
Example #28
Source File: JaxRsWebApplicationExceptionHandlerListenerTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void constructor_throws_IllegalArgumentException_if_passed_null_utils() {
    // when
    Throwable ex = Assertions.catchThrowable(new ThrowableAssert.ThrowingCallable() {
        @Override
        public void call() throws Throwable {
            new JaxRsWebApplicationExceptionHandlerListener(testProjectApiErrors, null);
        }
    });

    // then
    assertThat(ex).isInstanceOf(IllegalArgumentException.class);
}
 
Example #29
Source File: TraceAndSpanIdGeneratorTest.java    From wingtips with Apache License 2.0 5 votes vote down vote up
@Test
public void generateId_should_return_16_char_length_string_that_can_be_parsed_into_a_long_when_interpreted_as_a_64_bit_unsigned_hex_long() {
    Set<Character> charactersFromIds = new HashSet<>();

    for (int i = 0; i < 10000; i++) {
        // given: String ID value generated by generateId()
        final String idVal = TraceAndSpanIdGenerator.generateId();

        // then: that ID has 16 characters and can be interpreted as a 64 bit unsigned hex long and parsed into a Java long primitive
        assertThat(idVal).hasSize(16);
        Throwable parseException = catchThrowable(new ThrowableAssert.ThrowingCallable() {
            @Override
            public void call() throws Throwable {
                new BigInteger(idVal, 16).longValue();
            }
        });
        assertThat(parseException).isNull();

        // Store the characters we see in this ID in a set so we can verify later that we've only ever seen hex-compatible characters.
        for (char c : idVal.toCharArray()) {
            charactersFromIds.add(c);
        }
    }

    // We should have only run into lowercase hex characters, and given how many IDs we generated we should have hit all the lowercase hex characters.
    assertThat(charactersFromIds).containsOnly('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
}
 
Example #30
Source File: NoOpJsr303ValidatorTest.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Test
public void unwrap_throws_ValidationException() {
    // when
    Throwable ex = catchThrowable(new ThrowableAssert.ThrowingCallable() {
        @Override
        public void call() throws Throwable {
            noOpValidator.unwrap(FooClass.class);
        }
    });

    // then
    assertThat(ex).isInstanceOf(ValidationException.class);
}