Java tutorial
//package com.java2s; import java.lang.reflect.Method; import java.text.SimpleDateFormat; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { private static final Pattern ARRAY_REF = Pattern.compile("(.*)\\[(\\d+)\\]"); private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("d/M/yyyy HH:mm"); private static boolean match(String methodName, Object o, Object... fieldNamesAndExpectedValues) { boolean matches = true; for (int i = 0; matches && i < fieldNamesAndExpectedValues.length; i += 2) { String fieldName = (String) fieldNamesAndExpectedValues[i]; Object expectedValue = fieldNamesAndExpectedValues[i + 1]; Object actualValue = getValue(o, fieldName); if (expectedValue == null) { matches = (actualValue == null); } else { matches = actualValue != null && actualValue.equals(expectedValue); } } if (!matches) { println("LearnTestUtils." + methodName + "(...).new ArgumentMatcher() {...}.matches()"); println(1, "<fieldName>: <actualValue> vs <expectedValue>"); for (int i = 0; i < fieldNamesAndExpectedValues.length; i += 2) { String fieldName = (String) fieldNamesAndExpectedValues[i]; Object expectedValue = fieldNamesAndExpectedValues[i + 1]; println(o, fieldName, expectedValue); } } return matches; } private static Object getValue(Object o, String fieldName) { try { Object value = o; for (String exp : fieldName.split("\\.")) { Method m; if (exp.endsWith("()")) { m = value.getClass().getMethod(exp.substring(0, exp.length() - 2)); } else if (ARRAY_REF.matcher(exp).matches()) { Matcher matcher = ARRAY_REF.matcher(exp); matcher.find(); String methodNameBody = getMethodNameBody(matcher.group(1)); int arrayIndex = Integer.parseInt(matcher.group(2)); value = ((Object[]) value.getClass().getMethod("get" + methodNameBody) .invoke(value))[arrayIndex]; m = null; } else { String methodNameBody = getMethodNameBody(exp); try { m = value.getClass().getMethod("get" + methodNameBody); } catch (NoSuchMethodException ex) { m = value.getClass().getMethod("is" + methodNameBody); } } if (m != null) value = m.invoke(value); } return value; } catch (Exception ex) { throw new RuntimeException(ex); } } private static void println(Object o, String fieldName, Object expectedValue) { Object value = getValue(o, fieldName); println(1, "o." + fieldName + ": " + value + " vs " + expectedValue + " (" + getAlternateFormat(value) + " vs " + getAlternateFormat(expectedValue) + ")"); } private static void println(int tabs, String s) { println("\t" + s); } public static void println(String s) { System.out.println(s); } private static String getMethodNameBody(String exp) { return exp.substring(0, 1).toUpperCase() + exp.substring(1); } private static String getAlternateFormat(Object value) { if (value == null) return null; String formatted = null; if (value instanceof Long) formatted = DATE_FORMAT.format(new Date((Long) value)); return formatted == null ? "" : formatted; } }