All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.junit.internal.ComparisonCriteria Maven / Gradle / Ivy

Go to download

JUnit is a regression testing framework written by Erich Gamma and Kent Beck. It is used by the developer who implements unit tests in Java.

There is a newer version: 4.11
Show newest version
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 {
	// TODO (Sep 8, 2008 4:36:12 PM): check structure

	/**
	 * 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 expecteds and
	 * actuals are null, they are considered equal.
	 * 
	 * @param message
	 *            the identifying message for the {@link AssertionError} (
	 *            null 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);
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy