java - Asserting that a Set contains objects with methods that return given values -


class has method, getid(), returns string.

class b has method, getcollection(), returns collection (the order undefined)

i want test validate returned collection contains instances of a, each return expected values getid()

public interface {     string getid (); }  public interface b {     collection<a> getcollection (); }  public class btest {      @test     public void test () {         b b = ( ... )         collection<a> collection = b.getcollection();         assertequals(3, collection.size());          string expid1 = "id1";         string expid2 = "id2";         string expid3 = "id3";          // there should 3 a's in collection, each returning         // 1 of expected values in getid()     }  } 

i can think of inelegant here. i'm using junit/hamcrest/mockito. if nicest solution means library, that's not problem

java-8 solution, enough elegant?

public class btest {      @test     public void test () {         b b = ( ... )         set<string> expectids = new hashset<>(arrays.aslist("id1","id2","id3"));         collection<a> collection = b.getcollection();         set<string> ids = collection.stream().map(a->a.getid()).collect(collectors.toset());          assertequals(3, collection.size());         assertequals(expectids, ids);      }  } 

edited:

assertj: http://joel-costigliola.github.io/assertj/assertj-core-features-highlight.html

public class btest {      @test     public void test () {         b b = ( ... )         collection<a> collection = b.getcollection();          assertequals(3, collection.size());         assertthat(collection).extracting("id").contains("id1","id2","id3");     } } 

Comments