1 package org.junit.internal;
2 
3 import java.util.ArrayList;
4 import java.util.List;
5 
6 import org.junit.Assert;
7 
8 /**
9  * Thrown when two array elements differ
10  *
11  * @see Assert#assertArrayEquals(String, Object[], Object[])
12  */
13 public class ArrayComparisonFailure extends AssertionError {
14 
15     private static final long serialVersionUID = 1L;
16 
17     /*
18      * We have to use the f prefix until the next major release to ensure
19      * serialization compatibility.
20      * See https://github.com/junit-team/junit4/issues/976
21      */
22     private final List<Integer> fIndices = new ArrayList<Integer>();
23     private final String fMessage;
24     private final AssertionError fCause;
25 
26     /**
27      * Construct a new <code>ArrayComparisonFailure</code> with an error text and the array's
28      * dimension that was not equal
29      *
30      * @param cause the exception that caused the array's content to fail the assertion test
31      * @param index the array position of the objects that are not equal.
32      * @see Assert#assertArrayEquals(String, Object[], Object[])
33      */
ArrayComparisonFailure(String message, AssertionError cause, int index)34     public ArrayComparisonFailure(String message, AssertionError cause, int index) {
35         this.fMessage = message;
36         this.fCause = cause;
37         initCause(fCause);
38         addDimension(index);
39     }
40 
addDimension(int index)41     public void addDimension(int index) {
42         fIndices.add(0, index);
43     }
44 
45     @Override
getCause()46     public synchronized Throwable getCause() {
47         return super.getCause() == null ? fCause : super.getCause();
48     }
49 
50     @Override
getMessage()51     public String getMessage() {
52         StringBuilder sb = new StringBuilder();
53         if (fMessage != null) {
54             sb.append(fMessage);
55         }
56         sb.append("arrays first differed at element ");
57         for (int each : fIndices) {
58             sb.append("[");
59             sb.append(each);
60             sb.append("]");
61         }
62         sb.append("; ");
63         sb.append(getCause().getMessage());
64         return sb.toString();
65     }
66 
67     /**
68      * {@inheritDoc}
69      */
70     @Override
toString()71     public String toString() {
72         return getMessage();
73     }
74 }
75