вторник, 11 октября 2011 г.

Mockito vararg matcher

Matcher:
public class Matchers {
	public static  Matcher vararg(T... expected) {
		return new VarargMatcherImpl(expected);
	}

	public static class VarargMatcherImpl extends ArgumentMatcher implements VarargMatcher {
		Object[] expected;

		public VarargMatcherImpl(Object[] val) {
			this.expected = val;
		}

		@Override
		public boolean matches(Object arg) {
			boolean retval = false;
			if(arg != null && expected != null) {
				if(arg instanceof Object[]) {
					Object[] argArray = (Object[])arg;
					retval = Arrays.equals(argArray, expected);
				} else {
					if(expected.length == 1) {
						retval = expected[0].equals(arg);
					}
				}
			} else {
				retval = arg == null && expected == null;
			}

			return retval;
		}

		@Override
		public void describeTo(Description description) {
			description.appendText("[vararg should be : " + Arrays.toString(expected) + "]");
		}
	}
}
Use:
when(authorityGroupDao.findGroupsByRoles(argThat(vararg(roles)))).thenReturn(authorityGroupList);