*/
package org.wamblee.test;
+import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import junit.framework.TestCase;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
/**
* Useful assertions for use in test cases.
*
* @author Erik Brakkee
*/
public final class AssertionUtils {
+
+ private static final Log LOG = LogFactory.getLog(AssertionUtils.class);
/**
* Disabled constructor.
private AssertionUtils() {
// Empty
}
-
+
/**
* Asserts that two object arrays are equal.
*
* @param aActual
* Actual object array.
*/
- public static void assertEquals(Object[] aExpected, Object[] aActual) {
+ public static <T> void assertEquals(T[] aExpected, T[] aActual) {
assertEquals("", aExpected, aActual);
}
+
/**
* Asserts that two object arrays are equal.
* @param aActual
* Actual array.
*/
- public static void assertEquals(String aMsg, Object[] aExpected,
- Object[] aActual) {
- TestCase.assertEquals(aMsg + ": Array lengths ", aExpected.length,
+ public static <T> void assertEquals(String aMsg, T[] aExpected,
+ T[] aActual) {
+ TestCase.assertEquals(aMsg + " expected " +
+ Arrays.asList(aExpected) + ", actual " +
+ Arrays.asList(aActual) + ": Array lengths ", aExpected.length,
aActual.length);
for (int i = 0; i < aExpected.length; i++) {
aActual[i]);
}
}
+
/**
* Asserts that two objects are equal, and in case the object is an Object[]
* @param aActual
* Actual result.
*/
- public static void assertEquals(String aMsg, Object aExpected,
- Object aActual) {
+ public static <T> void assertEquals(String aMsg, T aExpected,
+ T aActual) {
if (aExpected instanceof Object[]) {
AssertionUtils.assertEquals(aMsg, (Object[]) aExpected,
(Object[]) aActual);
* @param aActual
* Actual result.
*/
- public static void assertEquals(String aMsg, Map aExpectedMap, Map aActual) {
+ public static <Key,Value> void assertEquals(String aMsg,
+ Map<Key,Value> aExpectedMap, Map<Key,Value> aActual) {
TestCase.assertEquals("Map sizes differ", aExpectedMap.size(), aActual
.size());
aExpectedMap.get(key), aActual.get(key));
}
}
+
+ public static interface ErroneousCode {
+ void run() throws Exception;
+ }
+
+ /**
+ * Asserts that an exception occurs.
+ * @param aRunnable Test cases should create a subclass of this which contains the
+ * code that should throw an exception.
+ * @param aType Type of exception that is expected.
+ */
+ public static void assertException(ErroneousCode aObject, Class aType) {
+ try {
+ aObject.run();
+ throw new RuntimeException("No exception occurred");
+ } catch (Throwable t) {
+ if ( aType.isInstance(t)) {
+ LOG.info("Expected exception occured " + t.getMessage());
+ return; // ok
+ }
+ else {
+ throw new RuntimeException(t);
+ }
+ }
+ }
}