assertThat:如何反转 containsString

assertThat: how to invert containsString

我有一个断言,用于检查当前所选文本中是否存在字符串:

import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.containsString;
assertThat(latest.getText(), containsString(targetString));

但是我找不到正确的方法来编写断言来检查字符串是否不包含在文本中。

我试过了

assertThat(latest.getText(), not(containsString(targetString)));

但出现错误

the method not(Matcher <String>) is undefined

有什么方法可以做到这一点?

您可以切换到 AssertJ 然后使用

assertThat(latest.getText()).doesNotContain(targetString);

对我来说,这是有效的,但会引发错误:

import static org.junit.Assert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;

class Main {
  public static void main(String[] args) {
    String test = "qwerty";
    String contained = "ert";
    assertThat(test, not(containsString(contained)));
  }
}