How do I negate assertions in AssertJ?

社会主义新天地 提交于 2019-12-12 10:49:56

问题


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();

回答1:


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.




回答2:


This will do the trick:

assertThat(Collections.singleton("1234xxx5678")).noneSatisfy(candidate -> 
    assertThat(candidate).containsOnlyDigits()
);

Slightly hacky, and the clarity of intention is not quite up to normal assertJ standards, but for the completely general case of negating any assertion it is what we have so far.

A fluent not() would be confusing when combined with chained asserts, but I do wish we could have a general doesNotSatisfy(Consumer) on AbstractObjectAssert



来源:https://stackoverflow.com/questions/37994008/how-do-i-negate-assertions-in-assertj

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!