Wachirawit Iedchoo
Wachirawit Iedchoo

Reputation: 61

jUnit - how to assert that a value not equals to both of another values

I used hamcrest library to test the code and I want to assert that the actual value(the first argument) not equals to both of 2 specified values("bad" and "good" in equalTo method). It should pass the test if the actual value (first argument of assertThat method) not equals to "good" and not equals to "bad". so I tried the following statement :

 @Test
public void valueNotEqualToBoth() {
    assertThat("good", not(allOf(equalTo("bad"), equalTo("good"))));
}

but it turns out that it pass the test but What I excepted is it shouldn't. because the first argument is equals to "good".

Upvotes: 6

Views: 8361

Answers (3)

GhostCat
GhostCat

Reputation: 140447

Simple: just ensure that the actual value (turned into a one-element set) isn't contained in some expected collection.

assertThat(Collections.singleton("good"), not(hasItem(Arrays.asList("bad", "good"))));

Upvotes: 1

user1230680
user1230680

Reputation:

From what I get from your question you do not want the provided value to be in the list of preset values right?

If that is what you want you are using the wrong combination of assertions.

assertThat("good", not(anyOf(equalTo("good"), equalTo("bad")));

The code above will tell you if the first parameter in the assertThat does not match any of the matchers in the second group of matchers.

Explanation of the new assertion is as follows:

  1. this will check if the provided value "good" matches any of the values "good" or "bad" (the anyOf matcher)
  2. it will invert the result of that match so true becomes false and false becomes true (the not matcher)
  3. it will throw an AssertionException if the not matcher results in not true, hence if it is anyOf the provided matchers in step 1 an exception is thrown.

Upvotes: 8

developer_hatch
developer_hatch

Reputation: 16224

If I understood your question, is something like

assertEquals("good", !somethingToTest.equals("bad") && !somethingToTest.equals("good"));

Upvotes: 0

Related Questions