org.opentest4j.AssertionFailedError Java Examples

The following examples show how to use org.opentest4j.AssertionFailedError. 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: DiffRepository.java    From calcite with Apache License 2.0 6 votes vote down vote up
public void assertEquals(String tag, String expected, String actual) {
  final String testCaseName = getCurrentTestCaseName(true);
  String expected2 = expand(tag, expected);
  if (expected2 == null) {
    update(testCaseName, expected, actual);
    throw new AssertionError("reference file does not contain resource '"
        + expected + "' for test case '" + testCaseName + "'");
  } else {
    try {
      // TODO jvs 25-Apr-2006:  reuse bulk of
      // DiffTestCase.diffTestLog here; besides newline
      // insensitivity, it can report on the line
      // at which the first diff occurs, which is useful
      // for largish snippets
      String expected2Canonical =
          expected2.replace(Util.LINE_SEPARATOR, "\n");
      String actualCanonical =
          actual.replace(Util.LINE_SEPARATOR, "\n");
      Assertions.assertEquals(expected2Canonical, actualCanonical, tag);
    } catch (AssertionFailedError e) {
      amend(expected, actual);
      throw e;
    }
  }
}
 
Example #2
Source File: TomlBackedConfigurationTest.java    From incubator-tuweni with Apache License 2.0 6 votes vote down vote up
@Test
void validatorNotCalledWhenDefaultUsed() throws Exception {
  SchemaBuilder builder = SchemaBuilder.create();
  builder.addString("fooS", "hello", null, (key, position, value) -> {
    throw new AssertionFailedError("should not be reached");
  });
  builder.addInteger("fooI", 2, null, (key, position, value) -> {
    throw new AssertionFailedError("should not be reached");
  });
  builder.addLong("fooL", 2L, null, (key, position, value) -> {
    throw new AssertionFailedError("should not be reached");
  });
  builder.addListOfString("fooLS", Collections.emptyList(), null, (key, position, value) -> {
    throw new AssertionFailedError("should not be reached");
  });
  builder.addListOfInteger("fooLI", Collections.emptyList(), null, (key, position, value) -> {
    throw new AssertionFailedError("should not be reached");
  });
  builder.addListOfLong("fooLL", Collections.emptyList(), null, (key, position, value) -> {
    throw new AssertionFailedError("should not be reached");
  });

  Schema schema = builder.toSchema();
  Configuration config = Configuration.fromToml("\n", schema);
  assertFalse(config.hasErrors());
}
 
Example #3
Source File: GeneratedClassNameParameterResolver.java    From doma with Apache License 2.0 6 votes vote down vote up
@Override
public Object resolveParameter(
    ParameterContext parameterContext, ExtensionContext extensionContext)
    throws ParameterResolutionException {
  if (isExternalDomain) {
    String name =
        clazz.isArray()
            ? clazz.getComponentType().getName() + EXTERNAL_DOMAIN_TYPE_ARRAY_SUFFIX
            : clazz.getName();
    return ClassNames.newExternalDomainTypeClassName(name).toString();
  }
  if (clazz.isAnnotationPresent(Dao.class)) {
    return clazz.getName() + Options.Constants.DEFAULT_DAO_SUFFIX;
  }
  if (clazz.isAnnotationPresent(Entity.class)) {
    return ClassNames.newEntityTypeClassName(clazz.getName()).toString();
  }
  if (clazz.isAnnotationPresent(Embeddable.class)) {
    return ClassNames.newEmbeddableTypeClassName(clazz.getName()).toString();
  }
  if (clazz.isAnnotationPresent(Domain.class)) {
    return ClassNames.newDomainTypeClassName(clazz.getName()).toString();
  }
  throw new AssertionFailedError("annotation not found.");
}
 
Example #4
Source File: TomlBackedConfigurationTest.java    From cava with Apache License 2.0 6 votes vote down vote up
@Test
void validatorNotCalledWhenDefaultUsed() throws Exception {
  SchemaBuilder builder = SchemaBuilder.create();
  builder.addString("fooS", "hello", null, (key, position, value) -> {
    throw new AssertionFailedError("should not be reached");
  });
  builder.addInteger("fooI", 2, null, (key, position, value) -> {
    throw new AssertionFailedError("should not be reached");
  });
  builder.addLong("fooL", 2L, null, (key, position, value) -> {
    throw new AssertionFailedError("should not be reached");
  });
  builder.addListOfString("fooLS", Collections.emptyList(), null, (key, position, value) -> {
    throw new AssertionFailedError("should not be reached");
  });
  builder.addListOfInteger("fooLI", Collections.emptyList(), null, (key, position, value) -> {
    throw new AssertionFailedError("should not be reached");
  });
  builder.addListOfLong("fooLL", Collections.emptyList(), null, (key, position, value) -> {
    throw new AssertionFailedError("should not be reached");
  });

  Schema schema = builder.toSchema();
  Configuration config = Configuration.fromToml("\n", schema);
  assertFalse(config.hasErrors());
}
 
Example #5
Source File: TestUtil.java    From canon-sdk-java with MIT License 6 votes vote down vote up
public static <T extends Throwable> T assertExecutionThrows(Class<T> expectedType, Executable executable) {
    try {
        executable.execute();
    } catch (Throwable actualException) {
        if (actualException instanceof ExecutionException) {
            if (expectedType.isInstance(actualException.getCause())) {
                return (T) actualException.getCause();
            } else {
                throw new AssertionFailedError(String.format("expected: %s but was: %s", expectedType, actualException.getCause()));
            }
        } else {
            Assertions.fail(String.format("Unexpected exception thrown: %s", actualException));
        }
    }
    String message = String.format("Expected %s to be thrown, but nothing was thrown.", expectedType.getCanonicalName());
    throw new AssertionFailedError(message);
}
 
Example #6
Source File: InterceptedStaticMethodTest.java    From quarkus with Apache License 2.0 6 votes vote down vote up
@AroundInvoke
Object aroundInvoke(InvocationContext ctx) throws Exception {
    if (!Modifier.isStatic(ctx.getMethod().getModifiers())) {
        throw new AssertionFailedError("Not a static method!");
    }
    assertNull(ctx.getTarget());
    Object ret = ctx.proceed();
    if (ret != null) {
        if (ret instanceof String) {
            return "OK:" + ctx.proceed();
        } else if (ret instanceof Double) {
            return 42.0;
        } else {
            throw new AssertionFailedError("Unsupported return type: " + ret.getClass());
        }
    } else {
        VOID_INTERCEPTIONS.incrementAndGet();
        return ret;
    }
}
 
Example #7
Source File: TestAssertions.java    From sarl with Apache License 2.0 6 votes vote down vote up
/** Test if the actual collection/iterable contains at least the expected objects.
 *
 * @param actual the collection to test.
 * @param expected the expected objects.
 * @param message the error message.
 * @since 0.11
 */
public static void assertContainsAtLeastCollection(Iterable<?> actual, Iterable<?> expected, Supplier<String> message) {
	assertNotNull(actual);
	Collection<Object> la = new ArrayList<>();
	Iterables.addAll(la, actual);
	Collection<Object> le = new ArrayList<>();
	Iterables.addAll(le, expected);

	Iterator<?> it1 = la.iterator();
	while (it1.hasNext()) {
		Object ac = it1.next();
		it1.remove();
		if (ac != null) {
			le.remove(ac);
		}
	}

	if (!le.isEmpty()) {
		final String emsg = message != null ? "\n" + message.get() : "";
		throw new AssertionFailedError("Expecting the following elements:\n" + le.toString() + emsg,
				toString(expected),
				toString(actual));
	}
}
 
Example #8
Source File: AbstractExtraLanguageGeneratorTest.java    From sarl with Apache License 2.0 6 votes vote down vote up
public void assertTypeDefinition(String typeName, String expectedContent) {
	final OutputConfiguration configuration = getOutputConfiguration();
	if (configuration == null) {
		throw new AssertionFailedError("", expectedContent, "");
	}
	final String filename = typeName.replaceAll("\\.", "/") + ".py";
	final String key = "/" + CompilationTestHelper.PROJECT_NAME + "/" + configuration.getOutputDirectory() + "/" + filename;
	final Map<String, CharSequence> generatedResources = this.result.getAllGeneratedResources();
	CharSequence ocontent = generatedResources.get(key);
	final String content;
	if (ocontent == null) {
		content = ""; 
	} else {
		content = ocontent.toString();
	}
	assertEquals(expectedContent, ocontent);
}
 
Example #9
Source File: AssertConnectRecordTest.java    From connect-utils with Apache License 2.0 6 votes vote down vote up
@TestFactory
public Stream<DynamicTest> headerValueDifferent() {
  return genericTests.entrySet().stream()
      .map(e -> dynamicTest(SchemaKey.of(e.getKey()).toString(), () -> {
        assertThrows(AssertionFailedError.class, () -> {
          Header expected = mock(Header.class);
          when(expected.schema()).thenReturn(e.getKey());
          when(expected.value()).thenReturn(e.getValue());
          when(expected.key()).thenReturn("key");
          Header actual = mock(Header.class);
          when(actual.schema()).thenReturn(e.getKey());
          when(actual.value()).thenReturn("adisfnbasd");
          when(actual.key()).thenReturn("key");
          assertHeader(expected, actual);
        });
      }));
}
 
Example #10
Source File: AssertSchemaTest.java    From connect-utils with Apache License 2.0 6 votes vote down vote up
@TestFactory
public Stream<DynamicTest> assertSchema() {
  List<TestCase> tests = new ArrayList<>();
  of(tests, Schema.STRING_SCHEMA, Schema.STRING_SCHEMA, true);
  of(tests, Schema.STRING_SCHEMA, Schema.OPTIONAL_STRING_SCHEMA, false);
  of(tests, Schema.BYTES_SCHEMA, Decimal.schema(4), false);
  of(tests, null, null, true);
  of(tests, Schema.STRING_SCHEMA, null, false);
  of(tests, null, Schema.STRING_SCHEMA, false);

  return tests.stream().map(testCase -> dynamicTest(testCase.toString(), () -> {
    if (testCase.isEqual) {
      AssertSchema.assertSchema(testCase.expected, testCase.actual);
    } else {
      assertThrows(AssertionFailedError.class, () -> {
        AssertSchema.assertSchema(testCase.expected, testCase.actual);
      });
    }
  }));
}
 
Example #11
Source File: CustomPredicatesTest.java    From enmasse with Apache License 2.0 6 votes vote down vote up
@Test
void testNegativeAssertionPredicate() {
    Assertions.assertThrows(AssertionFailedError.class, () -> {
        isNotPresent(value).assertTrue("expected to fail");
    });
    Assertions.assertThrows(AssertionFailedError.class, () -> {
        isPresent(value).negate().assertTrue("expected to fail");
    });


    Assertions.assertThrows(AssertionFailedError.class, () -> {
        isPresent(empty).assertTrue("expected to fail");
    });

    Assertions.assertThrows(AssertionFailedError.class, () -> {
        from(text, v -> v != null && v.length() == 0).assertTrue("");
    });
}
 
Example #12
Source File: JUnit_BestPractice.java    From JUnit-5-Quick-Start-Guide-and-Framework-Support with MIT License 6 votes vote down vote up
/**
 * It may seem trivial, but they happen more often than you would assume.
 */
@Test
void wrongDelta() {
    assertNotEquals(0.9, DummyUtil.calculateTimesThree(0.3)); // --> That's why the delta is important

    // Using a 0.0 delta doesn't make much sense and JUnit 5 actively prevents it
    AssertionFailedError ex = assertThrows(AssertionFailedError.class,
            () -> assertEquals(20.9, DummyUtil.calculateTimesThree(19), 0.0));

    LOG.info(ex.toString());
    // org.opentest4j.AssertionFailedError: positive delta expected but was: <0.0>


    // With such a high delta the correctness of the calculation is no longer assured
    assertEquals(15.5, DummyUtil.calculateTimesThree(5.0), 0.5);
}
 
Example #13
Source File: DocumentationFormatterTest.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Assert formatting
 *
 * @param input the input.
 * @param expected the expected input.
 */
protected void assertSLFormatted(String input, final String expected) {
	String actual = this.formatter.formatSinglelineComment(input, "\t");
	if (!Strings.equal(expected, actual)) {
		throw new AssertionFailedError("not same formatting", expected, actual);
	}
}
 
Example #14
Source File: DocumentationFormatterTest.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Assert formatting
 *
 * @param input the input.
 * @param expected the expected input.
 */
protected void assertMLFormatted(String input, final String expected) {
	String actual = this.formatter.formatMultilineComment(input, "\t");
	if (!Strings.equal(expected, actual)) {
		throw new AssertionFailedError("not same formatting", expected, actual);
	}
}
 
Example #15
Source File: TestAssertions.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Assert the actual object is a not-null instance of the given type.
 *
 * @param actualExpression the expected type.
 * @param expectedType the instance.
 * @param message the error message.
 */
public static void assertInstanceOf(Class<?> expected, Object actual, Supplier<String> message) {
	String m = (message == null) ? null : message.get();
	if (Strings.isNullOrEmpty(m)) {
		m = "Unexpected object type.";
	}
	if (actual == null) {
		fail(m);
	} else if (!expected.isInstance(actual)) {
		throw new AssertionFailedError(
				m,
				expected.getName(),
				actual.getClass().getName());
	}
}
 
Example #16
Source File: DocumentationFormatterTest.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Assert formatting
 *
 * @param input the input.
 * @param expected the expected input.
 */
protected void assertSLFormatted(String input, final String expected) {
	String actual = this.formatter.formatSinglelineComment(input);
	if (!Strings.equal(expected, actual)) {
		throw new AssertionFailedError("not same formatting", expected, actual);
	}
}
 
Example #17
Source File: DefaultActionPrototypeProviderTest.java    From sarl with Apache License 2.0 5 votes vote down vote up
private static void assertPrototypes(
		List<InferredStandardParameter> parameters,
		Collection<Object[]> expected,
		Object[][] originalExpected) {
	Iterator<Object[]> iterator = expected.iterator();
	while (iterator.hasNext()) {
		if (matchPrototype(parameters, iterator.next())) {
			iterator.remove();
			return;
		}
	}
	throw new AssertionFailedError("Not same parameter prototype.",
			parameters.toString(), toString(originalExpected));
}
 
Example #18
Source File: TestAssertions.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Assert if the two OSGI version are equal.
 *
 * @param expected the expected value.
 * @param actual the actual value.
 */
public static void assertOsgiVersionEquals(Version expected, Version actual) {
	if (Objects.equal(expected, actual)) {
		return;
	}
	if (expected == null) {
		fail("Version not null");
	}
	if (actual == null) {
		fail("Unexpected null value");
	}
	if (expected.getMajor() == actual.getMajor()
			&& expected.getMinor() == actual.getMinor()
			&& expected.getMicro() == actual.getMicro()) {
		if (!Strings.isNullOrEmpty(expected.getQualifier())) {
			final String expectedQualifier = expected.getQualifier();
			if ("qualifier".equals(expectedQualifier)) {
				if (!Strings.isNullOrEmpty(actual.getQualifier())) {
					return;
				}
			}
			if (Objects.equal(expected, actual.getQualifier())) {
				return;
			}
		} else {
			return;
		}
	}
	throw new AssertionFailedError("Not same versions", expected.toString(), actual.toString());
}
 
Example #19
Source File: AbstractConfigTest.java    From night-config with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void nestedOrderedSetting() {
	Config.setInsertionOrderPreserved(true);
	testNestedValuesOrder(Config.inMemory());
	Config.setInsertionOrderPreserved(false);
	assertThrows(AssertionFailedError.class, ()->testNestedValuesOrder(Config.inMemory()));
}
 
Example #20
Source File: CriteriaGeneratedClassNameParameterResolver.java    From doma with Apache License 2.0 5 votes vote down vote up
@Override
public Object resolveParameter(
    ParameterContext parameterContext, ExtensionContext extensionContext)
    throws ParameterResolutionException {
  if (clazz.isAnnotationPresent(Entity.class)) {
    return ClassNames.newEntityMetamodelClassNameBuilder(clazz.getName(), prefix, suffix)
        .toString();
  }
  throw new AssertionFailedError("annotation not found.");
}
 
Example #21
Source File: AbstractConfigTest.java    From night-config with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void concurrentOrderedSetting() {
	Config.setInsertionOrderPreserved(true);
	testValuesOrder(Config.inMemoryConcurrent());
	Config.setInsertionOrderPreserved(false);
	assertThrows(AssertionFailedError.class, ()->testValuesOrder(Config.inMemoryConcurrent()));
}
 
Example #22
Source File: AbstractConfigTest.java    From night-config with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void orderedSetting() {
	Config.setInsertionOrderPreserved(true);
	assertTrue(Config.isInsertionOrderPreserved());
	testValuesOrder(Config.inMemory());
	Config.setInsertionOrderPreserved(false);
	assertFalse(Config.isInsertionOrderPreserved());
	assertThrows(AssertionFailedError.class, ()->testValuesOrder(Config.inMemory()));
}
 
Example #23
Source File: AbstractConfigTest.java    From night-config with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void nestedOrderedSetting() {
	Config.setInsertionOrderPreserved(true);
	testNestedValuesOrder(Config.inMemory());
	Config.setInsertionOrderPreserved(false);
	assertThrows(AssertionFailedError.class, ()->testNestedValuesOrder(Config.inMemory()));
}
 
Example #24
Source File: AbstractConfigTest.java    From night-config with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void concurrentOrderedSetting() {
	Config.setInsertionOrderPreserved(true);
	testValuesOrder(Config.inMemoryConcurrent());
	Config.setInsertionOrderPreserved(false);
	assertThrows(AssertionFailedError.class, ()->testValuesOrder(Config.inMemoryConcurrent()));
}
 
Example #25
Source File: AbstractConfigTest.java    From night-config with GNU Lesser General Public License v3.0 5 votes vote down vote up
@Test
public void orderedSetting() {
	Config.setInsertionOrderPreserved(true);
	assertTrue(Config.isInsertionOrderPreserved());
	testValuesOrder(Config.inMemory());
	Config.setInsertionOrderPreserved(false);
	assertFalse(Config.isInsertionOrderPreserved());
	assertThrows(AssertionFailedError.class, ()->testValuesOrder(Config.inMemory()));
}
 
Example #26
Source File: AbstractInstanceRepositoryTest.java    From spring-boot-admin with Apache License 2.0 5 votes vote down vote up
@Test
public void should_not_compute_if_not_present() {
	// given
	InstanceId instanceId = InstanceId.of("not-existent");

	// when
	StepVerifier
			.create(this.repository.computeIfPresent(instanceId,
					(key, application) -> Mono.error(new AssertionFailedError("Should not call any computation"))))
			.verifyComplete();

	// then
	StepVerifier.create(this.repository.find(instanceId)).verifyComplete();
}
 
Example #27
Source File: JUnit_BestPractice.java    From JUnit-5-Quick-Start-Guide-and-Framework-Support with MIT License 5 votes vote down vote up
@Test
void correctParameterOrder() {
    // Clear and useful fail-report ;)
    AssertionFailedError ex = assertThrows(AssertionFailedError.class,
            () -> assertEquals("Grapefruit", dummyFruits.get(2).getName()));
    // . . . . . . . . . . . . . . ^expected . . . . . . ^actual

    LOG.info(ex.toString());
    // org.opentest4j.AssertionFailedError: expected: <Grapefruit> but was: <Granny Smith Apple>

    // "Oh... my actual value is not what was expected? Well now I know what the problem is and I can fix it!"
}
 
Example #28
Source File: TimeoutExtension.java    From demo-junit-5 with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
private void failTestIfRanTooLong(ExtensionContext context, Long timeout) {
	long launchTime = loadLaunchTime(context);
	long elapsedTime = currentTimeMillis() - launchTime;

	if (elapsedTime > timeout) {
		String message = format(
				"Test '%s' was supposed to run no longer than %d ms but ran %d ms.",
				context.getDisplayName(), timeout, elapsedTime);
		throw new AssertionFailedError(message, timeout, elapsedTime);
	}
}
 
Example #29
Source File: DocumentationFormatterTest.java    From sarl with Apache License 2.0 5 votes vote down vote up
/** Assert formatting
 *
 * @param input the input.
 * @param expected the expected input.
 */
protected void assertMLFormatted(String input, final String expected) {
	String actual = this.formatter.formatMultilineComment(input);
	if (!Strings.equal(expected, actual)) {
		throw new AssertionFailedError("not same formatting", expected, actual);
	}
}
 
Example #30
Source File: ExpectedExceptionExtension.java    From demo-junit-5 with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
@Override
public void afterTestExecution(ExtensionContext context) throws Exception {
	switch(loadExceptionStatus(context)) {
		case WAS_NOT_THROWN:
			expectedException(context)
					.map(expected -> new AssertionFailedError("Expected exception " + expected + " was not thrown.", expected, null))
					.ifPresent(ex -> { throw ex; });
		case WAS_THROWN_AS_EXPECTED:
			// the exception was thrown as expected so there is nothing to do
		case WAS_THROWN_NOT_AS_EXPECTED:
			// an exception was thrown but of the wrong type;
			// it was rethrown in `handleTestExecutionException`
			// so there is nothing to do here
	}
}