【问题标题】:Spring MockMvc don't expect contentSpring MockMvc 不要期望内容
【发布时间】:2019-06-18 21:03:47
【问题描述】:

我正在尝试测试一个基于用户的 spring 安全角色返回内容的 thymeleaf 模板。

我正在检查某些内容是否不存在

@Autowired
private MockMvc mockMvc;

...

mockMvc.perform(get("/index"))
    .andExpect(status().isOk())
    .andExpect(content().string(containsString("This content should be shown.")))
    .andExpect(content().string(XXXXXXX("This content should not be shown")));

这可能吗?

【问题讨论】:

    标签: spring-mvc spring-security spring-test


    【解决方案1】:

    一种解决方案是使用 hamcrests CoreMatchers.not(....) 方法:

    @Test
    @WithMockUser(roles = "USER")
    public void loginWithRoleUserThenExpectUserSpecificContent() throws Exception {
        mockMvc.perform(get("/index"))
                .andExpect(status().isOk())
                .andExpect(content().string(containsString("This content is only shown to users.")))
                .andExpect(content().string(doesNotContainString("This content is only shown to administrators.")));
    }
    
    private Matcher<String> doesNotContainString(String s) {
        return CoreMatchers.not(containsString(s));
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-03
      • 2018-03-29
      • 1970-01-01
      • 1970-01-01
      • 2019-07-21
      • 2021-05-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多