gpt4 book ai didi

java - 网站的 JUnit 测试包含一个字符串或(独占)其他字符串

转载 作者:行者123 更新时间:2023-11-28 20:39:01 27 4
gpt4 key购买 nike

在一个 spring-mvc 项目中,我对索引/主页的内容进行了测试:

@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class HomePageTest {

@Autowired
private MockMvc mockMvc;

@Test
public void shouldContainStrings() throws Exception {
this.mockMvc.perform(get("/")).andDo(print()).andExpect(status().isOk())
.andExpect(content().string(containsString("Hello World")));
}
}

这个测试到目前为止工作正常。但是现在我想测试字符串“Login”或(不包括)“Logout”的出现,即我想测试这两个字符串中是否恰好有一个(不是零也不是两个)出现在内容中。我怎样才能匹配这个或条件?

我试过了

...
.andExpect(content().string(
either(containsString("Login")).or(containsString("Logout"))));
....

但这也不起作用(如果两个字符串都出现在页面中则不会报错)。

最佳答案

只要string()方法接受 Hamcrest 匹配器,我在这里看到两个选项:

  1. 要么自己实现类似 XOR 的匹配器(您可以将此答案用作引用 https://stackoverflow.com/a/29610402/1782379)...
  2. ...或使用复杂条件,如“其中任何一个,但不能同时使用”

    Matcher<String> matcher =
    allOf(
    is(either(containsString("Login")).or(containsString("Logout"))),
    is(not(allOf(containsString("Login"), containsString("Logout")))));
    assertThat("_Login_", matcher); // OK
    assertThat("_Logout_", matcher); // OK
    assertThat("_Login_Logout_", matcher); // FAIL
    assertThat("__", matcher); // FAIL

我个人更喜欢使用第二个选项。

关于java - 网站的 JUnit 测试包含一个字符串或(独占)其他字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41451362/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com