I have a test that sends and returns a few different values to the 'subtract' method. The first list contains the method's results. The second list contains the expected solutions. This looks a little clunky and doesn't look and/or feel very clean. Is there a way, with Hamcrest, to have the same test to be more concise? Perhaps have a smaller list declaration or having a list directly in the assertion.
@Test
public void verifySubtractWillReturnCorrectValues() {
List<Double> results = new ArrayList<Double>(Arrays.asList(
aCalc.subtract(14, 4),
aCalc.subtract(10.0, 1),
aCalc.subtract(0b1111, 0b0011),
aCalc.subtract(3.0F, 4.0F),
aCalc.subtract(1L, 1L)));
List<Double> solutions = new ArrayList<Double>() {{add(10.0); add(9.0); add(12.0); add(-1.0); add(0.0);}};
assertThat(results, equalTo(solutions));
}
In answer to the general question: 'how can I make a concise assertion on the contents of a collection' ...
Hamcrest could be used to make the assertion much more concise, for example:
assertThat(results, Matchers.hasItems(10.0, 9.0, 12.0, -1.0, 0.0));
assertThat(results, Matchers.containsInAnyOrder(10.0, 9.0, 12.0, -1.0, 0.0));
Similarly, with AssertJ:
assertThat(results).containsExactlyInAnyOrder(10.0, 9.0, 12.0, -1.0, 0.0);
However, your test seems to be asserting outputs for several discrete inputs to your subtract()
method. You could test these individually thereby removing the question of a 'assert on a collection' entirely. For example:
assertThat(aCalc.subtract(14, 4), is(10.0));
assertThat(aCalc.subtract(10.0, 1), is(9.0));
// ... etc