In my case, I was looking for a way to get rid of this in unit tests:
Point p = getAPoint(); assertEquals(p.getX(), 4, "x"); assertEquals(p.getY(), 6, "x");
As you can see, someone is testing the getAPoint method and checking that the coordinates are as expected, but in the description of each statement it was copied and not synchronized with what was marked. It would be better to write this only once.
From @ddan's ideas, I built a proxy solution using Mockito:
private<T> void assertPropertyEqual(final T object, final Function<T, ?> getter, final Object expected) { final String methodName = getMethodName(object.getClass(), getter); assertEquals(getter.apply(object), expected, methodName); } @SuppressWarnings("unchecked") private<T> String getMethodName(final Class<?> clazz, final Function<T, ?> getter) { final Method[] method = new Method[1]; getter.apply((T)Mockito.mock(clazz, Mockito.withSettings().invocationListeners(methodInvocationReport -> { method[0] = ((InvocationOnMock) methodInvocationReport.getInvocation()).getMethod(); }))); return method[0].getName(); }
No. I can just use
assertPropertyEqual(p, Point::getX, 4); assertPropertyEqual(p, Point::getY, 6);
and it is guaranteed that the statement description will be synchronized with the code.
Downside:
- Will be a little slower than above
- Mockito is required to work.
- It is unlikely that anything other than usecase above is useful.
However, it shows a way to do this.
yankee Jun 04 '16 at 14:05 2016-06-04 14:05
source share