我的问题与这些类似:
但
给定一个控制器方法签名:
public String setupForm(
@ModelAttribute("notification") Notification n, RedirectAttributes redirect)
并给出一个测试(使用 Mockito):
@Mock
private AddNotificationController handler;
@Test
public void get() throws Exception{
request.setRequestURI("/addNotification/save.do");
request.setMethod("GET");
adapter.handle(request, response, handler);
verify(handler,times(1)).setupForm(any(Notification.class), any(RedirectAttributes.class));
}
执行时出现异常:
org.springframework.web.bind.annotation.support.HandlerMethodInvocationException:
Failed to invoke handler method [public java.lang.String ep.rdp.web.AddNotificationController.setupForm(a.b.c.Notification,org.springframework.web.servlet.mvc.support.RedirectAttributes)];
nested exception is java.lang.IllegalStateException:
Argument [RedirectAttributes] is of type Model or Map but is not assignable from the actual model.
You may need to switch newer MVC infrastructure classes to use this argument.
实际上我知道问题并且知道如何通过正确设置弹簧而不是在单元测试中来解决。
所以问题是:我还必须在模拟中设置什么才能使其正常工作?
附加信息
基础设置模拟:
@Before
public void setup() {
// adapter = new AnnotationMethodHandlerAdapter();
adapter = new RequestMappingHandlerAdapter();
request = new MockHttpServletRequest();
/*
* needed for AnnotationMethodHandlerAdapter when resolving controlle level mapping
*/
request.setAttribute(HandlerMapping.INTROSPECT_TYPE_LEVEL_MAPPING, Boolean.TRUE);
response = new MockHttpServletResponse();
}
现实
- 使用 AnnotationMethodHandlerAdapter 时出现此症状。
当我使用 RequestMappingHandlerAdapter 我得到:
java.lang.ClassCastException:ep.rdp.web.CacheController$$EnhancerByMockitoWithCGLIB$$d8aab2c0 不能在 org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter .java:80)