0

I have a Java Object that contains another java object that is a set. For Example:

Public States {
      private Set<City> cities = new HashSet(0);
       // Setters and Getters Here
      }

 Public City {
      private String dummyValue;
      // Setters and Getters Here
      }

I would like to test this object to ensure it contains values that I have modified in a method. For example I was trying:

Set<City> citySet = citySetInfoFromAnotherMethod;
assert citySet.iterator().next().equals("Dallas");

However I know this will not work because a Set does not have an order such as a list does.

So in conclusion, in what way can I test this object to see if values another method assigns to it appear after I do something to it.

DevelopingDeveloper
  • 883
  • 1
  • 18
  • 41

1 Answers1

2

You can use the excellent Hamcrest matchers library to achieve what you want (it ships built in with earlier versions of JUnit, but not with later ones).

You'll want to do something like:

Set<City> citySet = citySetInfoFromAnotherMethod;
assertThat(citySet, contains("Dallas"));

Of course that won't work because your set items are a City object, not a String, but you can use more Hamcrest matchers to achieve that too!

Set<City> citySet = citySetInfoFromAnotherMethod;
assertThat(citySet, contains(hasProperty("Name", eq("Dallas"))));

Alternatively (and IMHO better) approach would be to use a property matcher from Hamcrest to extract the City name.

tddmonkey
  • 20,798
  • 10
  • 58
  • 67