Skip to content

Instantly share code, notes, and snippets.

@artkoshelev
Last active August 29, 2015 14:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artkoshelev/1425e8f55cf583464529 to your computer and use it in GitHub Desktop.
Save artkoshelev/1425e8f55cf583464529 to your computer and use it in GitHub Desktop.
Hamcrest Matchers Working with collection problem
package my.system;
import java.util.ArrayList;
import java.util.List;
import org.hamcrest.FeatureMatcher;
import org.hamcrest.Matcher;
import org.junit.Test;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
public class HamcrestMatcherGist {
class SystemUser {
private String name;
private String nickName;
public String getName() {
return name;
}
public String getNickName() {
return nickName;
}
}
class SystemUserContainer {
private List<SystemUser> userList;
public List<SystemUser> getUserList() {
return userList;
}
}
static Matcher<SystemUser> withName(Matcher<String> nameMatcher) {
return new FeatureMatcher<SystemUser, String>(nameMatcher, "name", "name") {
@Override
protected String featureValueOf(SystemUser actual) {
return actual.getName();
}
};
}
static Matcher<SystemUserContainer> hasUserList(Matcher<Iterable<? extends SystemUser>> userListMatcher) {
return new FeatureMatcher<HamcrestMatcherGist.SystemUserContainer, Iterable<? extends SystemUser>>
(userListMatcher, "user list", "user list") {
@Override
protected Iterable<? extends SystemUser> featureValueOf(
SystemUserContainer actual) {
return actual.getUserList();
}
};
}
@Test
public void workingWithCollections() {
SystemUserContainer userContainer = new SystemUserContainer();
assertThat(userContainer, hasUserList(contains(withName(equalTo("Chuck")))));
assertThat(userContainer, hasUserList(hasSize(1)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment