Spring MVC 单元测试 - 如何使用 hamcrest 匹配器
Spring MVC Unit Test - how to use hamcrest matcher
我正在尝试为 MVC 控制器方法编写一个简单的测试用例。
我想测试视图名称是否包含字符串。
我想我需要这个版本的名称匹配器:
public ResultMatcher name(org.hamcrest.Matcher<? super String> matcher)
取自这里:
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/web/servlet/result/ViewResultMatchers.html#name-org.hamcrest.Matcher-
但是我该如何使用它呢?我无法计算出正确的语法...
(此表达式的 Matchers.contains("web_tmpl") 部分的语法错误:
this.mockMvc.perform(MockMvcRequestBuilders.get("/content/2"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.view().name(Matchers.contains("web_tmpl")))
;
您应该为
添加静态导入
import static org.hamcrest.Matchers.containsString;
并使用
.andExpect(view().name(containsString("web_tmpl")))
如果您使用的是 Maven,则依赖项是
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
我正在尝试为 MVC 控制器方法编写一个简单的测试用例。
我想测试视图名称是否包含字符串。
我想我需要这个版本的名称匹配器:
public ResultMatcher name(org.hamcrest.Matcher<? super String> matcher)
取自这里:
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/web/servlet/result/ViewResultMatchers.html#name-org.hamcrest.Matcher-
但是我该如何使用它呢?我无法计算出正确的语法...
(此表达式的 Matchers.contains("web_tmpl") 部分的语法错误:
this.mockMvc.perform(MockMvcRequestBuilders.get("/content/2"))
.andExpect(MockMvcResultMatchers.status().isOk())
.andExpect(MockMvcResultMatchers.view().name(Matchers.contains("web_tmpl")))
;
您应该为
添加静态导入import static org.hamcrest.Matchers.containsString;
并使用
.andExpect(view().name(containsString("web_tmpl")))
如果您使用的是 Maven,则依赖项是
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>