@Override public int compare(Method o1, Method o2) { String n1 = o1.getName().toLowerCase(), n2 = o2.getName().toLowerCase(); if (n1.contains("dispose") || n1.contains("close")) return 1; if (n2.contains("dispose") || n2.contains("close")) return -1; return n1.compareTo(n2); }
/** * Calls all public methods declared in the class corresponding to the given object. Does not * include methods from superclasses. * * @param object object to call the public methods on * @param comparator method comparator, allows running the methods in a specific order * @return list of methods invoked, including the parameters used for calling them */ private static List<MethodInvocation> callPublicMethodsInOrder( Object object, Comparator<Method> comparator) { try { List<MethodInvocation> invocations = new ArrayList<>(); Method[] methods = object.getClass().getDeclaredMethods(); if (comparator != null) Arrays.sort(methods, comparator); for (Method method : methods) { if (Modifier.isStatic(method.getModifiers()) || !Modifier.isPublic(method.getModifiers())) continue; Object[] params = new Object[method.getParameterTypes().length]; for (int i = 0; i < method.getParameterTypes().length; i++) { params[i] = instantiateType(method.getParameterTypes()[i]); } method.invoke(object, params); invocations.add(new MethodInvocation(method.getName(), params)); } return invocations; } catch (Exception ex) { ex.printStackTrace(); assertTrue( "Error calling public methods on object " + object + " (" + object.getClass().getSimpleName() + ")", false); return new ArrayList<>(); } }
/** * Check that all methods declared in the given interface were called. Does *not* include * methods from super interfaces. * * @return this for fluent api */ public MethodCallTester<MonitoredClass> assertAllInterfaceMethodsCalled() { List<MethodInvocation> currentInvocation = new ArrayList<>(invocations); // Debugger calling toString can mess with this for (Method method : mockClass.getDeclaredMethods()) { if (Modifier.isStatic(method.getModifiers()) || !Modifier.isPublic(method.getModifiers())) continue; boolean called = false; for (MethodInvocation invocation : currentInvocation) { if (invocation.method.equals(method.getName())) { called = true; break; } } assertTrue( "Method " + mockClass.getSimpleName() + "." + method.getName() + " was not called", called); } return this; }