org.junit.jupiter.api.function.ThrowingConsumer Java Examples

The following examples show how to use org.junit.jupiter.api.function.ThrowingConsumer. 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: StreamExampleTest.java    From mastering-junit5 with Apache License 2.0 6 votes vote down vote up
@Disabled
@TestFactory
Stream<DynamicTest> streamTest() {
    // Input data
    Integer array[] = { 1, 2, 3 };
    Iterator<Integer> inputGenerator = Arrays.asList(array).iterator();

    // Display names
    Function<Integer, String> displayNameGenerator = (
            input) -> "Data input:" + input;

    // Test executor
    ThrowingConsumer<Integer> testExecutor = (input) -> {
        System.out.println(input);
        assertTrue(input % 2 == 0);
    };

    // Returns a stream of dynamic tests
    return stream(inputGenerator, displayNameGenerator, testExecutor);
}
 
Example #2
Source File: ArchitectureTest.java    From taskana with Apache License 2.0 6 votes vote down vote up
@TestFactory
Stream<DynamicTest> commonClassesShouldNotDependOnOtherDomainClasses() {
  Stream<String> packagesToTest =
      TASKANA_SUB_PACKAGES.stream()
          .map(p -> p.split("\\.")[2])
          .distinct()
          .filter(d -> !"common".equals(d))
          .map(d -> ".." + d + "..");
  ThrowingConsumer<String> testMethod =
      p ->
          noClasses()
              .that()
              .haveNameNotMatching(".*TaskanaEngine.*")
              .and()
              .haveSimpleNameNotEndingWith("AbstractTaskanaJob")
              .and()
              .resideInAPackage("..common..")
              .should()
              .dependOnClassesThat()
              .resideInAPackage(p)
              .check(importedClasses);
  return DynamicTest.stream(
      packagesToTest.iterator(), p -> p + " should not be used by common", testMethod);
}
 
Example #3
Source File: ArchitectureTest.java    From taskana with Apache License 2.0 6 votes vote down vote up
@TestFactory
Stream<DynamicTest> classesShouldNotDependOnMonitorDomainClasses() {
  Stream<String> packagesToTest =
      TASKANA_SUB_PACKAGES.stream()
          .map(p -> p.split("\\.")[2])
          .distinct()
          .filter(d -> !"monitor".equals(d))
          .map(d -> ".." + d + "..");

  ThrowingConsumer<String> testMethod =
      p ->
          noClasses()
              .that()
              .resideInAPackage(p)
              .and()
              .haveNameNotMatching(".*TaskanaEngine.*")
              .should()
              .dependOnClassesThat()
              .resideInAnyPackage("..monitor..")
              .check(importedClasses);
  return DynamicTest.stream(
      packagesToTest.iterator(),
      p -> String.format("Domain %s should not depend on monitor", p),
      testMethod);
}
 
Example #4
Source File: StreamExampleTest.java    From Mastering-Software-Testing-with-JUnit-5 with MIT License 6 votes vote down vote up
@TestFactory
Stream<DynamicTest> streamTest() {
    // Input data
    Integer array[] = { 1, 2, 3 };
    Iterator<Integer> inputGenerator = Arrays.asList(array).iterator();

    // Display names
    Function<Integer, String> displayNameGenerator = (
            input) -> "Data input:" + input;

    // Test executor
    ThrowingConsumer<Integer> testExecutor = (input) -> {
        System.out.println(input);
        assertTrue(input % 2 == 0);
    };

    // Returns a stream of dynamic tests
    return stream(inputGenerator, displayNameGenerator, testExecutor);
}
 
Example #5
Source File: DynamicTestsUnitTest.java    From tutorials with MIT License 6 votes vote down vote up
@TestFactory
Stream<DynamicTest> dynamicTestsFromStream() {

    // sample input and output
    List<String> inputList = Arrays.asList("www.somedomain.com", "www.anotherdomain.com", "www.yetanotherdomain.com");
    List<String> outputList = Arrays.asList("154.174.10.56", "211.152.104.132", "178.144.120.156");

    // input generator that generates inputs using inputList
    Iterator<String> inputGenerator = inputList.iterator();

    // a display name generator that creates a different name based on the input
    Function<String, String> displayNameGenerator = (input) -> "Resolving: " + input;

    // the test executor, which actually has the logic of how to execute the test case
    DomainNameResolver resolver = new DomainNameResolver();
    ThrowingConsumer<String> testExecutor = (input) -> {
        int id = inputList.indexOf(input);
        assertEquals(outputList.get(id), resolver.resolveDomain(input));
    };

    // combine everything and return a Stream of DynamicTest
    return DynamicTest.stream(inputGenerator, displayNameGenerator, testExecutor);
}
 
Example #6
Source File: DynamicTests.java    From javatech with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@TestFactory
Stream<DynamicTest> generateRandomNumberOfTests() {

    // Generates random positive integers between 0 and 100 until
    // a number evenly divisible by 7 is encountered.
    Iterator<Integer> inputGenerator = new Iterator<Integer>() {

        Random random = new Random();

        int current;

        @Override
        public boolean hasNext() {
            current = random.nextInt(100);
            return current % 7 != 0;
        }

        @Override
        public Integer next() {
            return current;
        }
    };

    // Generates display names like: input:5, input:37, input:85, etc.
    Function<Integer, String> displayNameGenerator = (input) -> "input:" + input;

    // Executes tests based on the current input value.
    ThrowingConsumer<Integer> testExecutor = (input) -> assertTrue(input % 7 != 0);

    // Returns a stream of dynamic tests.
    return DynamicTest.stream(inputGenerator, displayNameGenerator, testExecutor);
}
 
Example #7
Source File: ArchitectureTest.java    From taskana with Apache License 2.0 5 votes vote down vote up
@TestFactory
Stream<DynamicTest> everySubPackageShouldBeFreeOfCyclicDependencies() {
  Stream<String> packagesToTest = TASKANA_SUB_PACKAGES.stream().map(s -> s + ".(*)..");
  ThrowingConsumer<String> testMethod =
      p -> slices().matching(p).should().beFreeOfCycles().check(importedClasses);
  return DynamicTest.stream(
      packagesToTest.iterator(),
      p -> p.replaceAll(Pattern.quote("pro.taskana."), "") + " is free of cycles",
      testMethod);
}
 
Example #8
Source File: SlackMarkdownTests.java    From roboslack with Apache License 2.0 5 votes vote down vote up
private static ThrowingConsumer<ValueDecorator<String>> stringDecoratorConsumer(String input) {
    return decorator -> {
        String expectedDecorated = decorator.prefix().orElse("")
                + input
                + decorator.suffix().orElse("");
        assertThat(decorator.decorate(input), is(equalTo(expectedDecorated)));
        assertThat(decorator.decorate(expectedDecorated), is(equalTo(expectedDecorated)));
    };
}
 
Example #9
Source File: SlackMarkdownTests.java    From roboslack with Apache License 2.0 5 votes vote down vote up
private static ThrowingConsumer<TupleDecorator<URL, String>> tupleUrlStringDecoratorConsumer(URL inputUrl,
        String inputText) {
    return decorator -> {
        String expectedDecorated = decorator.prefix().orElse("")
                + inputUrl.toString()
                + decorator.separator()
                + inputText
                + decorator.suffix().orElse("");
        assertThat(decorator.decorate(inputUrl, inputText), is(equalTo(expectedDecorated)));
    };
}
 
Example #10
Source File: BlockchainIntegrationTest.java    From exonum-java-binding with Apache License 2.0 5 votes vote down vote up
private void testKitTest(ThrowingConsumer<Blockchain> test) {
  Snapshot view = testKit.getSnapshot();
  Blockchain blockchain = Blockchain.newInstance(view);
  try {
    test.accept(blockchain);
  } catch (Throwable t) {
    fail(t);
  }
}
 
Example #11
Source File: AbstractCredentialsServiceTest.java    From hono with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Assert credentials.
 *
 * @param ctx The test context to report to.
 * @param tenantId The tenant to check for.
 * @param deviceId The device to check for.
 * @param authId The authentication id to check for.
 * @param type The credentials type to check for.
 * @param mangementValidation The validation logic for the management data.
 * @param adapterValidation The validation logic for the protocol adapter data.
 * @param whenComplete Call when this assertion was successful.
 */
protected void assertGet(final VertxTestContext ctx,
        final String tenantId, final String deviceId, final String authId, final String type,
        final ThrowingConsumer<OperationResult<List<CommonCredential>>> mangementValidation,
        final ThrowingConsumer<CredentialsResult<JsonObject>> adapterValidation,
        final ExecutionBlock whenComplete) {

    getCredentialsManagementService().readCredentials(tenantId, deviceId, NoopSpan.INSTANCE)
            .onComplete(ctx.succeeding(s3 -> ctx.verify(() -> {

                // assert a few basics, optionals may be empty
                // but must not be null
                assertNotNull(s3.getCacheDirective());
                assertResourceVersion(s3);

                mangementValidation.accept(s3);

                getCredentialsService().get(
                        tenantId,
                        type,
                        authId,
                        CLIENT_CONTEXT)
                        .onComplete(ctx.succeeding(s4 -> ctx.verify(() -> {

                            adapterValidation.accept(s4);

                            whenComplete.apply();
                        })));

            })));

}
 
Example #12
Source File: BaseOperatorTest.java    From reactor-core with Apache License 2.0 5 votes vote down vote up
private Stream<DynamicTest> toDynamicTests(
		List<? extends OperatorScenario<I, PI, O, PO>> scenarios,
		ThrowingConsumer<OperatorScenario<I, PI, O, PO>> executable
) {
	return scenarios.stream().map(scenario -> {
		return toDynamicTest(scenario, () -> {
			executable.accept(scenario);
		});
	});
}
 
Example #13
Source File: DynamicTests.java    From tutorials with MIT License 5 votes vote down vote up
@TestFactory
public Stream<DynamicTest> dynamicUserTestCollection() {
    List<User> inputList = Arrays.asList(new User("[email protected]", "John"), new User("[email protected]", "Ana"));

    Function<User, String> displayNameGenerator = (input) -> "Saving user: " + input;

    UserDAO userDAO = new UserDAO();
    ThrowingConsumer<User> testExecutor = (input) -> {
        userDAO.add(input);
        assertNotNull(userDAO.findOne(input.getEmail()));
    };

    return DynamicTest.stream(inputList.iterator(), displayNameGenerator, testExecutor);
}
 
Example #14
Source File: MoreReflection.java    From roboslack with Apache License 2.0 4 votes vote down vote up
@SuppressWarnings("unchecked")
public static <T> ThrowingConsumer<Method> noArgStaticFactoryConsumer(Consumer<T> delegateConsumer) {
    return staticFactoryMethod -> delegateConsumer.accept((T) staticFactoryMethod.invoke(null));
}