Java 如何用spring验证junit中的方法调用typsafe?
如何用类型安全表达式替换Java 如何用spring验证junit中的方法调用typsafe?,java,spring,junit,spring-test,Java,Spring,Junit,Spring Test,如何用类型安全表达式替换方法名(“getEmployeeDetailsById”)?以某种方式直接链接到类的方法。可能吗 @RunWith(SpringRunner.class) @WebMvcTest public class MyTest { @Test public void test() { mockMvc .perform(get("/employee/details/9816")) .andExpect(handler().hand
方法名(“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?
}
通过在类中的所有方法中搜索@GetMapping注释(我假设此处使用的注释,根据需要进行调整),可以在控制器中找到值为“/employee/details/{id}”的方法:
private String findMethodName() {
List<Method> methods =
new ArrayList<>(Arrays.asList(EmployeeController.class.getMethods());
for (Method method : methods) {
if (method.isAnnotationPresent(GetMapping.class)) {
GetMapping annotation = method.getAnnotation(GetMapping.class);
if(Arrays.asList(annotation.value())
.contains("/employee/details/{id}") {
return method.getName();
}
}
}
}
如果我没有误解您的意图,您希望以静态的方式构建期望 您可以使用spring&来实现您的目标,例如:
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 ---^
)
@RequestMapping("/foo")
public Object handlerReturnViewName() {
// ^--- use the super type instead
return "bar";
}
但有一件事你需要注意,那就是你会的。当您使处理程序方法返回字符串
视图名称时,您应该使处理程序方法的返回类型具有字符串
类的超类型(超级接口或超类),因为它是final,不能由cglib代理。例如:
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 ---^
)
@RequestMapping("/foo")
public Object handlerReturnViewName() {
// ^--- use the super type instead
return "bar";
}