aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/junit/internal/ArrayComparisonFailure.java
blob: d300e7e5866b3b16c31c7217ce41e9f2f8a8bfa1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package org.junit.internal;

import java.util.ArrayList;
import java.util.List;

import org.junit.Assert;

/**
 * Thrown when two array elements differ
 *
 * @see Assert#assertArrayEquals(String, Object[], Object[])
 */
public class ArrayComparisonFailure extends AssertionError {

    private static final long serialVersionUID = 1L;

    /*
     * We have to use the f prefix until the next major release to ensure
     * serialization compatibility.
     * See https://github.com/junit-team/junit4/issues/976
     */
    private final List<Integer> fIndices = new ArrayList<Integer>();
    private final String fMessage;
    private final AssertionError fCause;

    /**
     * Construct a new <code>ArrayComparisonFailure</code> with an error text and the array's
     * dimension that was not equal
     *
     * @param cause the exception that caused the array's content to fail the assertion test
     * @param index the array position of the objects that are not equal.
     * @see Assert#assertArrayEquals(String, Object[], Object[])
     */
    public ArrayComparisonFailure(String message, AssertionError cause, int index) {
        this.fMessage = message;
        this.fCause = cause;
        initCause(fCause);
        addDimension(index);
    }

    public void addDimension(int index) {
        fIndices.add(0, index);
    }

    @Override
    public synchronized Throwable getCause() {
        return super.getCause() == null ? fCause : super.getCause();
    }

    @Override
    public String getMessage() {
        StringBuilder sb = new StringBuilder();
        if (fMessage != null) {
            sb.append(fMessage);
        }
        sb.append("arrays first differed at element ");
        for (int each : fIndices) {
            sb.append("[");
            sb.append(each);
            sb.append("]");
        }
        sb.append("; ");
        sb.append(getCause().getMessage());
        return sb.toString();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String toString() {
        return getMessage();
    }
}