Since you are using JUnit, as of v4.4 the library can use the hamcrest matcher library which offers a rich DSL for building test expressions. This means you can remove the loop entirely and write a single assertion, testing for the existence of all expected values.
For example, hamcrest has a built-in function hasItems()
(documentation link for v1.3.RC2 but v1.3 is out - sorry couldn't find an up to date link).
import java.util.List;
import java.util.Arrays;
import static org.hamcrest.Matchers.hasItems;
import static org.junit.Assert.assertThat;
@Test
public void bothValuesShouldBePresent() {
List<Integer> itemValues = Arrays.asList(new Integer[]{ 0, 1, 2, 3 });
Integer[] expected = { 0, 1 };
assertThat(itemValues, hasItems(expected));
}
This, of course, assumes you can modify your getItems()
method to return a simple List<Integer>
.
Finally, depending on the version of JUnit you are using, hamcrest may or may not be bundled. JUnit inlined hamcrest-core between v4.4 and v4.10. Since it was just the hamcrest-core, I explicitly added the hamcrest-all dependency in my projects. As of JUnit v4.11 hamcrest is no longer inlined (much better IMHO) so you will always need to explicitly add the dependency if you want to use the matchers.
Also, here is a useful blog post on hamcrest collection matching.
Edit:
I have tried to think of what your getItems()
might return and here is an updated test example. Note that you need to turn the expected value into an array - see Why doesn't this code attempting to use Hamcrest's hasItems compile?
@Test
public void bothValuesShouldBePresent() {
List lt1 = new ArrayList();
lt1.add(0);
lt1.add(1);
List lt2 = new ArrayList();
List fakeGetItems = new ArrayList() {{ add(new HashMap<String, Integer>() {{ put("item", 0); }}); add(new HashMap<String, Integer>() {{ put("item", 1); }} ); }};
for (Object a : fakeGetItems) {
HashMap b = (HashMap)a;
lt2.add(b.get("item"));
}
assertThat(lt2, hasItems(lt1.toArray(new Integer[lt1.size()])));
}