java - 如何使用spring验证junit中的方法调用typsafe?

标签 java spring junit spring-test

如何用类型安全表达式替换 methodName("getEmployeeDetailsById")?以某种方式直接链接到类的方法。这可能吗?

@RunWith(SpringRunner.class)
@WebMvcTest
public class MyTest {
  @Test
  public void test() {
      mockMvc
        .perform(get("/employee/details/9816"))
        .andExpect(handler().handlerType(EmployeeController.class))
        .andExpect(handler().methodName("getEmployeeDetailsById")); //TODO typesafe?
  }

最佳答案

如果我没有误解你的意图,你想以静态方式建立期望。

您可以使用 spring HandlerResultMatchers#methodCall & MvcUriComponentsBuilder#on实现你的方式,例如:

mockMvc.perform(get("/employee/details/9816")).andExpect(
  handler().methodCall(on(EmployeeController.class).getEmployeeDetailsById(args))
  // args is any of the arbitrary value just to make the code to compile ---^
)

但是您需要注意的一件事是 MvcUriComponentsBuilder#oncreate a proxy to be able to inspect the previous invocations 。当您使处理程序方法返回 String View 名称时,您应该将处理程序方法的返回类型设置为其其父类(super class)型( super 接口(interface)或父类(super class)) >String 类,因为它是 final 且不能由 cglib 代理。例如:

@RequestMapping("/foo")
public Object handlerReturnViewName() {
  //    ^--- use the super type instead
  return "bar";
}

关于java - 如何使用spring验证junit中的方法调用typsafe?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47227091/

相关文章:

java - 从表中选择并插入到另一个表中

javascript - 使用二进制数据通过 AJAX 从 jsPDF 上传 PDF

java - Maven:是否可以在另一个项目的编译范围中包含一个测试 jar

安卓单元测试: How to mock an object which contains MutableLiveData but only exposes LiveData?

android - 使用 Matchers.anyObject() 验证挂起函数

java - Thunderbird api 通过 Java 发送邮件

java - 获取 org.dom4j.DocumentException : feature read only while deploying war file in tomcat of linux 异常

java - Camel - 捕获全局 onException 中抛出的异常

java - Spring 表达式语言 - 在注释中获取系统属性

java - bash -c遇到参数麻烦