在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匹配器,我就会在这里看到两个选项:
...或使用复杂的条件,例如“其中任何一个,但不能同时使用两者”
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
我个人更喜欢使用第二种选择。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句