如何用类型安全表达式替换 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#on将create 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/