001package org.junit.internal;
002
003import java.util.ArrayList;
004import java.util.List;
005
006import org.junit.Assert;
007
008/**
009 * Thrown when two array elements differ
010 *
011 * @see Assert#assertArrayEquals(String, Object[], Object[])
012 */
013public class ArrayComparisonFailure extends AssertionError {
014
015    private static final long serialVersionUID = 1L;
016
017    /*
018     * We have to use the f prefix until the next major release to ensure
019     * serialization compatibility.
020     * See https://github.com/junit-team/junit4/issues/976
021     */
022    private final List<Integer> fIndices = new ArrayList<Integer>();
023    private final String fMessage;
024    private final AssertionError fCause;
025
026    /**
027     * Construct a new <code>ArrayComparisonFailure</code> with an error text and the array's
028     * dimension that was not equal
029     *
030     * @param cause the exception that caused the array's content to fail the assertion test
031     * @param index the array position of the objects that are not equal.
032     * @see Assert#assertArrayEquals(String, Object[], Object[])
033     */
034    public ArrayComparisonFailure(String message, AssertionError cause, int index) {
035        this.fMessage = message;
036        this.fCause = cause;
037        initCause(fCause);
038        addDimension(index);
039    }
040
041    public void addDimension(int index) {
042        fIndices.add(0, index);
043    }
044
045    @Override
046    public synchronized Throwable getCause() {
047        return super.getCause() == null ? fCause : super.getCause();
048    }
049
050    @Override
051    public String getMessage() {
052        StringBuilder sb = new StringBuilder();
053        if (fMessage != null) {
054            sb.append(fMessage);
055        }
056        sb.append("arrays first differed at element ");
057        for (int each : fIndices) {
058            sb.append("[");
059            sb.append(each);
060            sb.append("]");
061        }
062        sb.append("; ");
063        sb.append(getCause().getMessage());
064        return sb.toString();
065    }
066
067    /**
068     * {@inheritDoc}
069     */
070    @Override
071    public String toString() {
072        return getMessage();
073    }
074}