Skip to content

Instantly share code, notes, and snippets.

@dmcg
Created March 4, 2015 22:21
Show Gist options
  • Save dmcg/2be1699a04a5c3784298 to your computer and use it in GitHub Desktop.
Save dmcg/2be1699a04a5c3784298 to your computer and use it in GitHub Desktop.
ValueExpectations
private User activeUser(Customer customer) {
return mock(User.class,
"isAccountNonLocked", true,
"isEnabled", true,
"isAccountNonExpired", true,
"isPasswordProvided", true,
"isCredentialsNonExpired", true,
"getCustomer", customer,
"getAuthorities", ImmutableList.of()
);
}
public <T> T mock(Class<T> clas, Object... pairs) {
T result = mockery.mock(clas);
mockery.checking(new ValueExpectations(result, pairs));
return result;
}
public class ValueExpectations implements ExpectationBuilder {
private final Iterable<Map.Entry<String, Object>> values;
private final Object subject;
public ValueExpectations(Object subject, Iterable<Map.Entry<String, Object>> values) {
this.subject = subject;
this.values = values;
}
public <T> ValueExpectations(T subject, Object... pairs) {
this(subject, mapEntriesFor(pairs));
}
@Override
public void buildExpectations(Action action, ExpectationCollector expectationCollector) {
for (Map.Entry<String, Object> value : values) {
expectationCollector.add(expecationBuilderFor(value.getKey(), value.getValue()).toExpectation(action));
}
}
private InvocationExpectationBuilder expecationBuilderFor(String name, Object value) {
InvocationExpectationBuilder builder = new InvocationExpectationBuilder();
builder.of(subject);
builder.method(name);
builder.setAction(new ReturnValueAction(value));
return builder;
}
private static Iterable<Map.Entry<String, Object>> mapEntriesFor(Object[] pairs) {
if (pairs.length % 2 != 0)
throw new IllegalArgumentException("argument must be pairs");
List<Map.Entry<String, Object>> result = Lists.newArrayListWithCapacity(pairs.length / 2);
for (int i = 0; i < pairs.length;) {
result.add(Pair.of((String)pairs[i++], pairs[i++]));
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment