【问题标题】:assertThat: how to invert containsStringassertThat:如何反转 containsString
【发布时间】:2023-03-10 11:06:01
【问题描述】:

我有一个断言检查当前选择的文本中是否存在字符串:

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

这样做的方法是什么?

【问题讨论】:

  • notorg.hamcrest.Matchers.not 的导入吗?
  • !containsString(targetString)
  • 不:我也试过了,但它说'操作员!未定义匹配器类型 Matcher '
  • 谢谢乔,确实有效。我投了赞成票,因为 a 不能接受它作为答案。

标签: java hamcrest


【解决方案1】:

对我来说这是可行的,但会引发错误:

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

【讨论】:

    【解决方案2】:

    你可以切换到AssertJ然后使用

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

    【讨论】:

      猜你喜欢
      • 2014-12-12
      • 2018-11-02
      • 1970-01-01
      • 2021-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多