87

Using the hamcrest library for Java, what's a nicely readable way to do the opposite of:

assertThat(someCollection, hasItem(someItem))

I want to make sure someCollection does not contain item someItem

harschware
  • 13,006
  • 17
  • 55
  • 87

3 Answers3

153

Negate the hasItem assertion

assertThat(someCollection, not(hasItem(someItem)))
dee-see
  • 23,668
  • 5
  • 58
  • 91
  • 16
    Once I imported the package IsNot (`import static org.hamcrest.core.IsNot.not`) it worked well. – harschware Feb 20 '12 at 03:32
  • The `Matcherzs` defines all of the. factory methods so you can have a single `*` static import. I'll look it up a work if no one else posts the line in the next hour. – David Harkness Feb 20 '12 at 17:58
  • 6
    @harschware - From the [basic tutorial](http://code.google.com/p/hamcrest/wiki/Tutorial), `import static org.hamcrest.MatcherAssert.assertThat;` and `import static org.hamcrest.Matchers.*;` – David Harkness Feb 20 '12 at 18:19
  • 3
    In hamcrest version 1.3- assertThat(someCollection, not(hasItem(someItem))) didn't work so I used assertThat(someCollection, not(contains(someItem))) – nik Jul 19 '21 at 12:16
7

If you need to Assert an Array, the same logic use not(hasItemInArray())

final String[] availableIds = {"123", "321"};
final String userId = "333";

softAssert.assertThat("Id not found", availableIds, not(hasItemInArray(userId)));
softAssert.assertAll();
Enigo
  • 3,685
  • 5
  • 29
  • 54
Sashko
  • 191
  • 3
  • 10
-3

or you can do;

.extract().jsonPath().getObject("data", pojo.class);  
(above is response)

assertThat(response, not(hasItem(bodyYouArePosting)));