Search code examples
assertj

How do I negate assertions in AssertJ?


Using Hamcrest it is easily possible to negate a matcher. E.g. you can write an assertion like this:

assertThat("The dog bites Tom", not(stringContainsInOrder(Arrays.asList("Tom", "dog"))));

I.e. using the org.hamcrest.core.IsNot , org.hamcrest.core.AnyOf matchers it is easy to combine or negate assertions.

Is there any equivalent in AssertJ? I know that it is possible to combine/negate Conditions. But what about normal assertion methods? E.g. what do you do if you want to test that a String does not consists only of digits, i.e. negate the following assertion:

assertThat("1234xxx5678").containsOnlyDigits();

Solution

  • It is not possible to combine normal assertions methods, this is an area where Hamcrest is more flexible than AssertJ.

    In your case I would write a Condition as you suggested or use a lambda with matches assertion.