0

I want to compare Collection (products) (in my case it is LinkedHashMap$LinkedValues) and ArrayList.

The test

assertThat(products, equalTo(Lists.newArrayList(product1, product2, product3)));

doesn't work because LinkedValues doesn't implement equals method. So I changed my test to:

  assertThat(new ArrayList<>(products), equalTo(Lists.newArrayList(product1, product2, product3)));

Is there a better solution where I do not have to check if the collection implements equals method?

AppiDevo
  • 3,195
  • 3
  • 33
  • 51

3 Answers3

1

Since you're using Hamcrest, you should use the slightly confusingly named method Matchers.contains(). It checks whether the target collection contains the same elements in the same order as the original collection.

Given

Map<String, String> linkedHashMap = new LinkedHashMap<>();
linkedHashMap.put("a", "A");
linkedHashMap.put("b", "B");

This will pass:

assertThat(linkedHashMap.values(), contains("A", "B"));

and this would fail:

assertThat(linkedHashMap.values(), contains("B", "A"));

Note that Hamcrest has been long dead and even though it works fine and is okay for 99% of usages, you will be shocked by how good AssertJ is, how much functionality it provides and how easy asserting can be.

With AssertJ:

assertThat(linkedHashMap.values()).containsExactly("A", "B");
Petr Janeček
  • 37,768
  • 12
  • 121
  • 145
  • 1
    Heh I checked `contains` before but as you said I understood wrong what it does. And thank you for recommending AssertJ. I checked it and it is great :) – AppiDevo Oct 25 '18 at 07:56
0

Assuming the data type you're using already has an equals method, then there's no need to check for an (un-)implemented equals() function. Otherwise, you would have to create something that compares the data you're using.

On a side note, the two lines of code you have are identical. Did you mean to put something else in the second line?

  • The lines shouldn't be identical. Sorry for my mistake. I edited the post. – AppiDevo Oct 23 '18 at 20:54
  • Awesome; so, like Mike just said, you could use a boolean expression, such as Arrays.equal and ensure that it should always evaluate to "true." Otherwise, for a custom object inside something like an ArrayList, you would need to define your own equals method, be it for the ArrayList (which i believe Java's API should have something for this) or for the object itself. – Ben Michalowicz Oct 23 '18 at 21:00
-1

You can use Arrays.equals:

assertTrue(Arrays.equals(products.toArray(), new Product[] {product1, product2, product3}));

This checks array sizes and odering of items. Your product class should implement equals() to be something meaningful.

Note that you can use ArrayList.toArray() to get an array if needed.

Mike
  • 4,722
  • 1
  • 27
  • 40