下面列出了org.mockito.exceptions.base.MockitoAssertionError#org.junit.ComparisonFailure 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 2nd order test to verify the framework correctly fails if a disconnect occurs It could have a
* more detailed exception check - more than just the class.
*/
@Test(expected = ComparisonFailure.class)
public void disconnectShouldThrow() throws Exception {
try (final TestNodeList txNodes = new TestNodeList()) {
// Create & Start Nodes
final TestNode node1 = txNodes.create(vertx, null, null, noDiscovery);
txNodes.create(vertx, null, null, noDiscovery);
txNodes.create(vertx, null, null, noDiscovery);
initTest(txNodes);
node1.network.getPeers().iterator().next().disconnect(DisconnectReason.BREACH_OF_PROTOCOL);
wrapup(txNodes);
}
}
/**
* assertQuery is almost the same as Assert.assertEquals except that it will allow for different orderings of the terms within an AND or and OR.
*
* @param expected
* The expected query
* @param query
* The query being tested
*/
protected void assertPlanEquals(String expected, String query) throws ParseException {
// first do the quick check
if (expected.equals(query)) {
return;
}
ASTJexlScript expectedTree = JexlASTHelper.parseJexlQuery(expected);
expectedTree = TreeFlatteningRebuildingVisitor.flattenAll(expectedTree);
ASTJexlScript queryTree = JexlASTHelper.parseJexlQuery(query);
queryTree = TreeFlatteningRebuildingVisitor.flattenAll(queryTree);
TreeEqualityVisitor.Reason reason = new TreeEqualityVisitor.Reason();
boolean equal = TreeEqualityVisitor.isEqual(expectedTree, queryTree, reason);
if (!equal) {
throw new ComparisonFailure(reason.reason, expected, query);
}
}
/**
* Asserts the current title is equal to the expectation string.
* @param webdriver the driver in use
* @param expected the expected object
* @throws Exception in case of failure
*/
protected void assertTitle(final WebDriver webdriver, final String expected) throws Exception {
final long maxWait = System.currentTimeMillis() + DEFAULT_WAIT_TIME;
while (true) {
try {
assertEquals(expected, webdriver.getTitle());
return;
}
catch (final ComparisonFailure e) {
if (System.currentTimeMillis() > maxWait) {
throw e;
}
Thread.sleep(10);
}
}
}
private void assertLog(final WebDriver driver, final String expected) throws InterruptedException {
final long maxWait = System.currentTimeMillis() + DEFAULT_WAIT_TIME;
while (true) {
try {
final String text = driver.findElement(By.id("log")).getAttribute("value").trim().replaceAll("\r", "");
assertEquals(expected, text);
return;
}
catch (final ComparisonFailure e) {
if (System.currentTimeMillis() > maxWait) {
throw e;
}
Thread.sleep(10);
}
}
}
protected void assertAttributesEquals(QName element,
Map<QName, String> q1,
Map<QName, String> q2,
Collection<String> ignoreAttr) {
for (Map.Entry<QName, String> attr : q1.entrySet()) {
if (ignoreAttr.contains(attr.getKey().getLocalPart())
|| ignoreAttr.contains(element.getLocalPart() + "@"
+ attr.getKey().getLocalPart())) {
continue;
}
String found = q2.get(attr.getKey());
if (found == null) {
throw new AssertionError("Attribute: " + attr.getKey()
+ " is missing in "
+ element);
}
if (!found.equals(attr.getValue())) {
throw new ComparisonFailure("Attribute not equal: ",
attr.getKey() + ":" + attr.getValue(),
attr.getKey() + ":" + found);
}
}
}
/**
* Display comparison view of test file with expected and actual xpect expectation
*/
private void displayComparisonView(ComparisonFailure cf, Description desc) {
IXpectURIProvider uriProfider = XpectRunner.INSTANCE.getUriProvider();
IFile fileTest = null;
if (uriProfider instanceof N4IDEXpectTestURIProvider) {
N4IDEXpectTestURIProvider fileCollector = (N4IDEXpectTestURIProvider) uriProfider;
fileTest = ResourcesPlugin.getWorkspace().getRoot()
.getFileForLocation(new Path(fileCollector.findRawLocation(desc)));
}
if (fileTest != null && fileTest.isAccessible()) {
N4IDEXpectCompareEditorInput inp = new N4IDEXpectCompareEditorInput(fileTest, cf);
CompareUI.openCompareEditor(inp);
} else {
throw new RuntimeException("paths in descriptions changed!");
}
}
public static void textMatches(
@NonNull Spanned spanned,
int start,
int end,
@NonNull TestSpan.Text text) {
final String expected = text.literal();
final String actual = spanned.subSequence(start, end).toString();
if (!expected.equals(actual)) {
throw new ComparisonFailure(
String.format(Locale.US, "Text mismatch at {start: %d, end: %d}", start, end),
expected,
actual
);
}
}
public static Matcher<PoetClass> generatesTo(String expectedTestFile) {
return new TypeSafeMatcher<PoetClass>() {
@Override
protected boolean matchesSafely(PoetClass spec) {
String expectedClass = getExpectedClass(spec, expectedTestFile);
String actualClass = generateClass(spec);
try {
assertThat(actualClass, equalToIgnoringWhiteSpace(expectedClass));
} catch (AssertionError e) {
//Unfortunately for string comparisons Hamcrest doesn't really give us a nice diff. On the other hand
//IDEs know how to nicely display JUnit's ComparisonFailure - makes debugging tests much easier
throw new ComparisonFailure(String.format("Output class does not match expected [test-file: %s]", expectedTestFile), expectedClass, actualClass);
}
return true;
}
@Override
public void describeTo(Description description) {
//Since we bubble an exception this will never actually get called
}
};
}
public static Matcher<ClassSpec> generatesTo(String expectedTestFile) {
return new TypeSafeMatcher<ClassSpec>() {
@Override
protected boolean matchesSafely(ClassSpec spec) {
String expectedClass = getExpectedClass(spec, expectedTestFile);
String actualClass = generateClass(spec);
try {
assertThat(actualClass, equalToIgnoringWhiteSpace(expectedClass));
} catch (AssertionError e) {
//Unfortunately for string comparisons Hamcrest doesn't really give us a nice diff. On the other hand
//IDEs know how to nicely display JUnit's ComparisonFailure - makes debugging tests much easier
throw new ComparisonFailure(String.format("Output class does not match expected [test-file: %s]", expectedTestFile), expectedClass, actualClass);
}
return true;
}
@Override
public void describeTo(Description description) {
//Since we bubble an exception this will never actually get called
}
};
}
protected void assertEquals(Set<byte[]> expected, Set<byte[]> actual) {
assertEquals(expected.size(), actual.size());
Iterator<byte[]> e = expected.iterator();
while (e.hasNext()) {
byte[] next = e.next();
boolean contained = false;
for (byte[] element : expected) {
if (Arrays.equals(next, element)) {
contained = true;
}
}
if (!contained) {
throw new ComparisonFailure("element is missing", Arrays.toString(next), actual.toString());
}
}
}
private void prepareTaskAs(Runnable runnable, String lastName) {
range(0, TIMES).forEach(i -> {
tasks.add(() -> {
Session.login(lastName);
try {
runnable.run();
} catch (ComparisonFailure failure) {
throw new ComparisonFailure(lastName + ": " + failure.getMessage(),
failure.getExpected(), failure.getActual());
} finally {
Session.logout();
}
return lastName;
});
});
}
public void assertFile(Request request, String responseFile) throws IOException {
String expectedResponse = IOUtils.readFile(new File(responsesPath + responseFile));
expectedResponse = include(expectedResponse);
expectedResponse = expectedResponse.replaceAll("(\"[^\"]*\")|\\s*", "$1"); // Remove whitespace
String responseString = container.handleRequest(request).getBodyAsString();
if (expectedResponse.contains("(ignore)")) {
// Convert expected response to a literal pattern and replace any ignored field with a pattern that matches
// until the first stop character
String stopCharacters = "[^,:\\\\[\\\\]{}]";
String expectedResponsePattern = Pattern.quote(expectedResponse)
.replaceAll("\"?\\(ignore\\)\"?", "\\\\E" +
stopCharacters + "*\\\\Q");
if (!Pattern.matches(expectedResponsePattern, responseString)) {
throw new ComparisonFailure(responseFile + " (with ignored fields)", expectedResponsePattern,
responseString);
}
} else {
assertEquals(responseFile, expectedResponse, responseString);
}
}
@Override
public String processFile(String completeData, String data, int offset, int len, String change) throws Exception {
IParseResult initialParseResult = parser.parse(new StringReader(data));
String newData = applyDelta(data, offset, len, change);
ReplaceRegion replaceRegion = new ReplaceRegion(offset, len, change);
try {
IParseResult reparsed = parser.reparse(initialParseResult, replaceRegion);
IParseResult parsedFromScratch = parser.parse(new StringReader(newData));
assertEqual(data, newData, parsedFromScratch, reparsed);
return newData;
} catch(Throwable e) {
ComparisonFailure throwMe = new ComparisonFailure(e.getMessage(), newData, replaceRegion + DELIM + data);
throwMe.initCause(e);
throw throwMe;
}
}
public static void assertEquals( Supplier<String> message, Object expected, Object actual )
{
if ( !Objects.equals( expected, actual ) )
{
if ( expected instanceof String && actual instanceof String )
{
String cleanMessage = message.get();
if ( cleanMessage == null )
{
cleanMessage = "";
}
throw new ComparisonFailure( cleanMessage, (String) expected, (String) actual );
}
else
{
fail( format( message.get(), expected, actual ) );
}
}
}
@Test
public void checkTopicDoesNotExistWithExistentTopicTest() {
String topic = "checktopicdoesnotexistwithexistenttopic";
Assertions.assertThatCode(() -> kafka_utils.createTopic(topic, null)).doesNotThrowAnyException();
Assertions.assertThatCode(() -> kafka_utils.checkTopicExists(topic)).doesNotThrowAnyException();
try {
kafka_utils.checkTopicDoesNotExist(topic);
}
catch (AssertionError|Exception e) {
Assertions.assertThat(e).isInstanceOf(ComparisonFailure.class);
Assertions.assertThat(e).hasMessage("[Topic " + topic + " exists.] expected:<[fals]e> but was:<[tru]e>");
}
Assertions.assertThatCode(() -> kafka_utils.deleteTopic(topic)).doesNotThrowAnyException();
Assertions.assertThatCode(() -> kafka_utils.checkTopicDoesNotExist(topic)).doesNotThrowAnyException();
}
/** Check if one of the markers has the given message part.
*
* @param messagePart
* @param markers
*/
protected void assertContainsMarker(String messagePart, IMarker... markers) {
StringBuilder markerText = new StringBuilder();
for (IMarker marker : markers) {
try {
String markerMsg = marker.getAttribute(IMarker.MESSAGE).toString();
if (markerMsg.contains(messagePart)) {
return;
}
markerText.append(markerMsg);
markerText.append("\n");
} catch (CoreException exception) {
//
}
}
throw new ComparisonFailure("Missed marker: " + messagePart,
messagePart,
markerText.toString());
}
public void assertEquals(String testCaseName, String tag, String expected, String actual) {
String expected2 = expand(testCaseName, 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");
Assert.assertEquals(
tag,
expected2Canonical,
actualCanonical);
} catch (ComparisonFailure e) {
amend(testCaseName, expected, actual);
throw e;
}
}
}
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");
Assert.assertEquals(
tag,
expected2Canonical,
actualCanonical);
} catch (ComparisonFailure e) {
amend(expected, actual);
throw e;
}
}
}
/**
* Asserts that two objects are equal. If they are not, an {@link AssertionError} is thrown with
* the given message. If <code>expected</code> and <code>actual</code> are <code>null</code>, they
* are considered equal.
*
* @param message the identifying message for the {@link AssertionError} (<code>null</code> okay)
* @param expected expected value
* @param actual actual value
*/
public static void assertEquals(String message, Object expected, Object actual) {
if (equalsRegardingNull(expected, actual)) {
return;
}
if (expected instanceof String && actual instanceof String) {
String cleanMessage = message == null ? "" : message;
throw new ComparisonFailure(cleanMessage, (String) expected, (String) actual);
} else {
failNotEquals(message, expected, actual);
}
}
private void test(final String... string) throws Exception {
final StringBuilder html = new StringBuilder(HtmlPageTest.STANDARDS_MODE_PREFIX_
+ "<html><head>\n"
+ "<script>\n"
+ " function test() {\n"
+ " var date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0));\n"
+ " try {\n");
for (int i = 0; i < string.length - 1; i++) {
html.append(string[i]).append("\n");
}
html.append(
" alert(" + string[string.length - 1] + ");\n"
+ " } catch(e) {alert('exception')}\n"
+ " }\n"
+ "</script>\n"
+ "</head><body onload='test()'>\n"
+ "</body></html>");
try {
loadPageWithAlerts2(html.toString());
}
catch (final ComparisonFailure e) {
final String msg = e.getMessage();
for (int i = 0; i < msg.length(); i++) {
final char c = msg.charAt(i);
if (CharUtils.isAscii(c)) {
System.out.print(c);
}
else {
System.out.print(CharUtils.unicodeEscaped(c));
}
}
System.out.println();
throw e;
}
}
private static int addExpectation(final List<String> lines, int i,
final String browserString, final ComparisonFailure comparisonFailure) {
while (!lines.get(i).startsWith(" @Alerts")) {
i--;
}
final List<String> alerts = CodeStyleTest.alertsToList(lines, i);
for (final Iterator<String> it = alerts.iterator(); it.hasNext();) {
if (it.next().startsWith(browserString + " = ")) {
it.remove();
}
}
alerts.add(browserString + " = " + getActualString(comparisonFailure));
lines.remove(i);
while (lines.get(i).startsWith(" ")) {
lines.remove(i);
}
Collections.sort(alerts);
for (int x = 0; x < alerts.size(); x++) {
String line = alerts.get(x);
if (x == 0) {
if (!line.contains(" = ")) {
line = "DEFAULT = " + line;
}
line = " @Alerts(" + line;
}
else {
line = " " + line;
}
if (x < alerts.size() - 1) {
line += ",";
}
else {
line += ")";
}
lines.add(i++, line);
}
return i;
}
/**
* Asserts the actual events with the expected ones.
*
* @param sessionId
* the unique ID of the session that has to be checked.
* @param expectedEvents
* the expected events to assert against the actual ones.
*/
public void assertEquals(final String sessionId, final Iterable<String> expectedEvents) {
assertNotNull("Queue was not initialized. One should call #init(int) before invoking #assertEquals()", latch);
try {
latch.await(20L, SECONDS);
unregisterSupplier.get();
} catch (final InterruptedException e) {
throw new AssertionError("Time out while waiting to receive all expected test events.", e);
}
final Collection<String> eventsForSession = events.get(sessionId);
if (size(expectedEvents) != eventsForSession.size()) {
throw new ComparisonFailure("Expected:", toString(expectedEvents), toString(eventsForSession));
}
final Iterator<String> actItr = eventsForSession.iterator();
final Iterator<String> expItr = expectedEvents.iterator();
while (expItr.hasNext()) {
if (!actItr.hasNext()) {
throw new ComparisonFailure("Expected:", toString(expectedEvents), toString(eventsForSession));
}
final String expected = expItr.next();
final String actual = actItr.next();
if (null == expected || null == actual) {
if (expected != actual) {
throw new ComparisonFailure("Expected:", toString(expectedEvents), toString(eventsForSession));
}
} else {
if (!expected.equals(actual)) {
throw new ComparisonFailure("Expected:", toString(expectedEvents), toString(eventsForSession));
}
}
Assert.assertEquals(expected, actual);
}
}
/**
*/
public N4IDEXpectCompareEditorInput(IFile file,
ComparisonFailure cf) {
super(createConfiguration(file));
Preconditions.checkNotNull(file);
this.file = file;
this.comparisonFailure = cf;
}
@Test
public void testIsIdenticalTo_withComparisonFailureForWhitespaces_throwsReadableMessage() {
// Expected Exception
expect(ComparisonFailure.class);
expectMessage("Expected child nodelist length '1' but was '3'");
expectMessage("expected:<<a>[<b/>]</a>> but was:<<a>[" + getLineSeparator() + " <b/>" + getLineSeparator() + "]</a>>");
// run test:
assertThat("<a>\n <b/>\n</a>", isIdenticalTo("<a><b/></a>").throwComparisonFailure());
}
private void assertHomeFolderLocation(String tenantDomain, final String username,
final String expectedPath) throws Exception
{
try
{
final String domainUsername = tenantService.getDomainUser(username, tenantDomain);
TenantUtil.runAsSystemTenant(new TenantRunAsWork<Object>()
{
public NodeRef doWork() throws Exception
{
NodeRef person = personService.getPerson(domainUsername, false);
NodeRef homeFolder = DefaultTypeConverter.INSTANCE.convert(NodeRef.class,
nodeService.getProperty(person, ContentModel.PROP_HOMEFOLDER));
if (expectedPath != null)
{
assertNotNull("User: "+domainUsername+" home folder should exist", homeFolder);
}
NodeRef rootPath = homeFolderManager.getRootPathNodeRef(largeHomeFolderProvider);
String actualPath = toPath(rootPath, homeFolder);
assertEquals("User: "+domainUsername+" home folder location", expectedPath, actualPath);
return null;
}
}, tenantDomain);
}
catch (RuntimeException e)
{
final Throwable cause = e.getCause();
if (cause instanceof ComparisonFailure || cause instanceof AssertionError)
{
throw (ComparisonFailure)cause;
}
else
{
throw e;
}
}
}
private void assertContains(String expected, Serializable actual)
{
String actualString = (String)actual;
if (actual == null || !actualString.contains(expected))
{
throw new ComparisonFailure("Expected not contained in actual.", expected, actualString);
}
}
@Test
public void testIsSimilarTo_withComparisonFormatterAndThrowComparisonFailure_shouldFailWithCustomMessage() {
// prepare testData
expect(ComparisonFailure.class);
expectMessage("DESCRIPTION");
expectMessage("DETAIL-[abc]");
expectMessage("DETAIL-[xyz]");
final String control = "<a><b attr=\"abc\"></b></a>";
final String test = "<a><b attr=\"xyz\"></b></a>";
// run test
assertThat(test, isSimilarTo(control).withComparisonFormatter(new DummyComparisonFormatter()).throwComparisonFailure());
}
public void fireproof(String input) throws Exception {
try {
EObject file = parseHelper.parse(input);
IResolvedTypes resolvedTypes = typeResolver.resolveTypes(file);
Assert.assertNotNull(resolvedTypes);
if (file != null) {
TreeIterator<EObject> allContents = file.eAllContents();
while (allContents.hasNext()) {
EObject content = allContents.next();
if (content instanceof XAbstractFeatureCall) {
assertExpressionTypeIsResolved(((XExpression) content), resolvedTypes);
XAbstractFeatureCall abstractFeatureCall = (XAbstractFeatureCall) content;
if (abstractFeatureCall.getImplicitReceiver() != null) {
assertExpressionTypeIsResolved(abstractFeatureCall.getImplicitReceiver(),
resolvedTypes);
}
if (abstractFeatureCall.getImplicitFirstArgument() != null) {
assertExpressionTypeIsResolved(abstractFeatureCall.getImplicitFirstArgument(),
resolvedTypes);
}
} else if (content instanceof XClosure) {
assertExpressionTypeIsResolved(((XExpression) content), resolvedTypes);
for (JvmFormalParameter it : ((XClosure) content).getImplicitFormalParameters()) {
assertIdentifiableTypeIsResolved(it, resolvedTypes);
}
} else if (content instanceof XExpression) {
assertExpressionTypeIsResolved(((XExpression) content), resolvedTypes);
} else if (content instanceof JvmIdentifiableElement) {
assertIdentifiableTypeIsResolved(((JvmIdentifiableElement) content), resolvedTypes);
}
}
}
} catch (Throwable e) {
ComparisonFailure error = new ComparisonFailure(e.getMessage(), input, "");
error.setStackTrace(e.getStackTrace());
throw error;
}
}
public void fireproof(String input) throws Exception {
try {
EObject file = parseHelper.parse(input);
IResolvedTypes resolvedTypes = typeResolver.resolveTypes(file);
Assert.assertNotNull(resolvedTypes);
if (file != null) {
TreeIterator<EObject> allContents = file.eAllContents();
while (allContents.hasNext()) {
EObject content = allContents.next();
if (content instanceof XAbstractFeatureCall) {
assertExpressionTypeIsResolved((XExpression) content, resolvedTypes);
XAbstractFeatureCall abstractFeatureCall = (XAbstractFeatureCall) content;
if (abstractFeatureCall.getImplicitReceiver() != null) {
assertExpressionTypeIsResolved(abstractFeatureCall.getImplicitReceiver(), resolvedTypes);
}
if (abstractFeatureCall.getImplicitFirstArgument() != null) {
assertExpressionTypeIsResolved(abstractFeatureCall.getImplicitFirstArgument(), resolvedTypes);
}
} else if (content instanceof XClosure) {
assertExpressionTypeIsResolved((XExpression) content, resolvedTypes);
for (JvmFormalParameter p : ((XClosure) content).getImplicitFormalParameters()) {
assertIdentifiableTypeIsResolved(p, resolvedTypes);
}
} else if (content instanceof XExpression) {
assertExpressionTypeIsResolved((XExpression) content, resolvedTypes);
} else if (content instanceof JvmIdentifiableElement) {
assertIdentifiableTypeIsResolved((JvmIdentifiableElement) content, resolvedTypes);
}
}
}
} catch (Throwable e) {
ComparisonFailure error = new ComparisonFailure(e.getMessage(), input, "");
error.setStackTrace(e.getStackTrace());
throw error;
}
}
protected void assertTagEquals(Tag expected, Tag source,
final List<String> ignoreAttr,
final List<String> ignoreTag) {
if (!expected.getName().equals(source.getName())) {
throw new ComparisonFailure("Tags not equal: ",
expected.getName().toString(),
source.getName().toString());
}
assertAttributesEquals(expected.getName(),
expected.getAttributes(), source.getAttributes(), ignoreAttr);
assertAttributesEquals(expected.getName(),
source.getAttributes(), expected.getAttributes(), ignoreAttr);
if (!StringUtils.isEmpty(expected.getText())
&& !expected.getText().equals(source.getText())) {
throw new ComparisonFailure("Text not equal: ",
expected.getText(),
source.getText());
}
if (!expected.getTags().isEmpty()) {
for (Tag expectedTag : expected.getTags()) {
if (ignoreTag.contains(expectedTag.getName().getLocalPart())
&& expectedTag.getTags().isEmpty()) {
continue;
}
Tag sourceTag = getFromSource(source, expectedTag);
if (sourceTag == null) {
throw new AssertionError("\n" + expectedTag.toString()
+ " is missing in the source file:"
+ "\n" + source.toString());
}
assertTagEquals(expectedTag, sourceTag, ignoreAttr, ignoreTag);
}
}
}