aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/org/junit/internal/ComparisonCriteria.java
blob: e97011d8dc857e4097b6e69def0687501806a36b (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
75
76
package org.junit.internal;

import java.lang.reflect.Array;

import org.junit.Assert;

/**
 * Defines criteria for finding two items "equal enough". Concrete subclasses
 * may demand exact equality, or, for example, equality within a given delta.
 */
public abstract class ComparisonCriteria {
	/**
	 * Asserts that two arrays are equal, according to the criteria defined by
	 * the concrete subclass. If they are not, an {@link AssertionError} is
	 * thrown with the given message. If <code>expecteds</code> and
	 * <code>actuals</code> are <code>null</code>, they are considered equal.
	 * 
	 * @param message
	 *            the identifying message for the {@link AssertionError} (
	 *            <code>null</code> okay)
	 * @param expecteds
	 *            Object array or array of arrays (multi-dimensional array) with
	 *            expected values.
	 * @param actuals
	 *            Object array or array of arrays (multi-dimensional array) with
	 *            actual values
	 */
	public void arrayEquals(String message, Object expecteds, Object actuals)
			throws ArrayComparisonFailure {
		if (expecteds == actuals)
			return;
		String header= message == null ? "" : message + ": ";

		int expectedsLength= assertArraysAreSameLength(expecteds,
				actuals, header);

		for (int i= 0; i < expectedsLength; i++) {
			Object expected= Array.get(expecteds, i);
			Object actual= Array.get(actuals, i);

			if (isArray(expected) && isArray(actual)) {
				try {
					arrayEquals(message, expected, actual);
				} catch (ArrayComparisonFailure e) {
					e.addDimension(i);
					throw e;
				}
			} else
				try {
					assertElementsEqual(expected, actual);
				} catch (AssertionError e) {
					throw new ArrayComparisonFailure(header, e, i);
				}
		}
	}

	private boolean isArray(Object expected) {
		return expected != null && expected.getClass().isArray();
	}

	private int assertArraysAreSameLength(Object expecteds,
			Object actuals, String header) {
		if (expecteds == null)
			Assert.fail(header + "expected array was null");
		if (actuals == null)
			Assert.fail(header + "actual array was null");
		int actualsLength= Array.getLength(actuals);
		int expectedsLength= Array.getLength(expecteds);
		if (actualsLength != expectedsLength)
			Assert.fail(header + "array lengths differed, expected.length="
					+ expectedsLength + " actual.length=" + actualsLength);
		return expectedsLength;
	}

	protected abstract void assertElementsEqual(Object expected, Object actual);
}