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/junit/issues/976
021     */
022    private final List<Integer> fIndices = new ArrayList<Integer>();
023    private final String fMessage;
024
025    /**
026     * Construct a new <code>ArrayComparisonFailure</code> with an error text and the array's
027     * dimension that was not equal
028     *
029     * @param cause the exception that caused the array's content to fail the assertion test
030     * @param index the array position of the objects that are not equal.
031     * @see Assert#assertArrayEquals(String, Object[], Object[])
032     */
033    public ArrayComparisonFailure(String message, AssertionError cause, int index) {
034        this.fMessage = message;
035        initCause(cause);
036        addDimension(index);
037    }
038
039    public void addDimension(int index) {
040        fIndices.add(0, index);
041    }
042
043    @Override
044    public String getMessage() {
045        StringBuilder sb = new StringBuilder();
046        if (fMessage != null) {
047            sb.append(fMessage);
048        }
049        sb.append("arrays first differed at element ");
050        for (int each : fIndices) {
051            sb.append("[");
052            sb.append(each);
053            sb.append("]");
054        }
055        sb.append("; ");
056        sb.append(getCause().getMessage());
057        return sb.toString();
058    }
059
060    /**
061     * {@inheritDoc}
062     */
063    @Override
064    public String toString() {
065        return getMessage();
066    }
067}