001 /*
002 * Created on Oct 10, 2007
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
005 * in compliance with the License. You may obtain a copy of the License at
006 *
007 * http://www.apache.org/licenses/LICENSE-2.0
008 *
009 * Unless required by applicable law or agreed to in writing, software distributed under the License
010 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
011 * or implied. See the License for the specific language governing permissions and limitations under
012 * the License.
013 *
014 * Copyright @2007-2011 the original author or authors.
015 */
016 package org.fest.assertions;
017
018 import static org.fest.util.Strings.*;
019 import static org.fest.util.ToString.toStringOf;
020
021 /**
022 * Creates instances of JUnit's <code>ComparisonFailure</code>.
023 *
024 * @author Yvonne Wang
025 * @author Alex Ruiz
026 */
027 public final class ComparisonFailureFactory {
028
029 private static final String EMPTY_MESSAGE = "";
030
031 private static ConstructorInvoker constructorInvoker = new ConstructorInvoker();
032
033 static void constructorInvoker(ConstructorInvoker newConstructorInvoker) {
034 constructorInvoker = newConstructorInvoker;
035 }
036
037 /**
038 * Creates a new instance of JUnit's <code>ComparisonFailure</code> only if JUnit 4+ is in the classpath.
039 * @param message the identifying message or {@code null}.
040 * @param expected the expected value.
041 * @param actual the actual value.
042 * @return the created <code>ComparisonFailure</code>, or {@code null} if JUnit 4+ is not in the classpath.
043 */
044 public static AssertionError comparisonFailure(String message, Object expected, Object actual) {
045 try {
046 return newComparisonFailure(clean(message), expected, actual);
047 } catch (Exception e) {
048 return null;
049 }
050 }
051
052 private static String clean(String message) {
053 return message == null ? "" : message;
054 }
055
056 private static AssertionError newComparisonFailure(String message, Object expected, Object actual) throws Exception {
057 String className = "org.junit.ComparisonFailure";
058 Class<?>[] parameterTypes = new Class<?>[] { String.class, String.class, String.class };
059 Object[] parameterValues = new Object[] { format(message), asString(expected), asString(actual) };
060 Object o = constructorInvoker.newInstance(className, parameterTypes, parameterValues);
061 if (o instanceof AssertionError) return (AssertionError)o;
062 return null;
063 }
064
065 private static String asString(Object o) {
066 if (o instanceof String) return quote((String)o);
067 if (o == null) return null;
068 return toStringOf(o);
069 }
070
071 private static String format(String message) {
072 if (isEmpty(message)) return EMPTY_MESSAGE;
073 return String.format("[%s]", message);
074 }
075
076 private ComparisonFailureFactory() {}
077 }