Java: How can I define an anonymous Hamcrest Matcher? -


i'm trying use junit / hamcrest assert collection contains @ least 1 element custom logic asserts true. i'm hoping there's kind of matcher 'anyof' takes lambda (or anonymous class definition) can define custom logic. i've tried typesafematcher can't figure out it.

i don't think anyof i'm looking either seem take list of matchers.

what testing? there's chance use combination of matchers hasitem, allof , hasproperty, otherwise implement org.hamcrest.typesafematcher. find looking @ source code of existing matchers helps. i've created basic custom matcher below matches on property

public static class foo {     private int id;     public foo(int id) {         this.id = id;     }     public int getid() {         return id;     } }  @test public void custommatcher() {     collection<foo> foos = arrays.aslist(new foo[]{new foo(1), new foo(2)});     assertthat(foos, hasitem(hasid(1)));     assertthat(foos, hasitem(hasid(2)));     assertthat(foos, not(hasitem(hasid(3)))); }  public static matcher<foo> hasid(final int expectedid) {     return new typesafematcher<foo>() {          @override         protected void describemismatchsafely(foo foo, description description) {             description.appendtext("was ").appendvalue(foo.getid());         }          @override         public void describeto(description description) {             description.appendtext("foo id ").appendvalue(expectedid);         }          @override         protected boolean matchessafely(foo foo) {             // custom matching logic goes here             return foo.getid() == expectedid;         }     }; } 

Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -