编写JUnit测试用例请求调度程序时出错
在为Request调度程序编写测试用例时,我遇到了一些错误。 我的课
@Override public void doFilter(ServletRequest request, ServletResponse resp, FilterChain chain) throws IOException, ServletException { if(isMockAccountEnabled()) { HttpServletRequest req = (HttpServletRequest)request; String reqUrl = req.getRequestURI(); ApiUserDetails userDetails = userBean.getUserDetails(); HttpSession session = req.getSession(); if(isThisTestAccount(reqUrl, session)) { log.info(userDetails); log.debug("Entering Test acount flow for the request "+reqUrl); RequestDispatcher dispatcher = req.getRequestDispatcher("/mock/" + EnumService.returnMockService(reqUrl)); dispatcher.forward(request, resp); } } }
测试用例写的
@Mock private FilterChain chain; @InjectMocks private MockAccountFilter mockAccountFilter = new MockAccountFilter(); MockHttpServletRequest request = new MockHttpServletRequest(); MockHttpServletResponse response = new MockHttpServletResponse(); MockHttpSession session = new MockHttpSession(); @Test public void filterRequestMockFirst() throws Exception { MockRequestDispatcher dispatcher =new MockRequestDispatcher("/mock/ABCTEST"); when(request.getRequestDispatcher("/mock/ABCTEST")).thenReturn(dispatcher); request.setRequestURI("/check/employee/123456/false"); mockAccountFilter.doFilter(request, response, chain); Assert.assertTrue(request.getRequestURI().contains("/mock/ABCTEST")); }
错误
when() requires an argument which has to be 'a method call on a mock'.
有人可以告诉我编写这个测试用例的确切方法。
我没有足够的信息告诉你“编写这个测试用例的确切方法”,并且StackOverflow不是修复大块代码的好地方,但我可以告诉你为什么你得到那个消息。 🙂
MockHttpServletRequest request = new MockHttpServletRequest();
这里有两种“模拟”的感觉:
-
Mockito提供的模拟是基于接口自动生成的,并使用静态方法(如何
when
和verify
。 Mockito模拟是使用Mockito.mock
创建的(或者@Mock
当且仅当您使用MockitoJUnitRunner
或MockitoAnnotations.initMocks
)。 -
名称以“Mock”开头的完整类(如
MockHttpServletRequest
)实际上是完整的类实现,它们实际上比通过J2EE实际获得的更容易变异或更改。 这些可能更准确地称为“假”,因为它们是用于测试的简单接口实现,不会validation行为并且无法通过Mockito工作。 您可以确定它们不是Mockito模拟器,因为您使用new MockHttpServletRequest();
实例化它们new MockHttpServletRequest();
。
例如,FilterChain可能会由Mockito提供。 MockHttpServletRequest request
不是Mockito模拟,这就是您收到错误消息的原因。
你最好的选择是选择一种类型的模拟或另一种模式 – 或者可以工作 – 并确保你正在使用when
语句(如果选择Mockito)或者像setRequestURI
这样的setter(如果你选择MockHttpSession
)正确地准备那些模拟 -风格嘲笑)。
看起来你正在使用Mockito进行unit testing。
正如消息告诉你做一个“when(…)”,你喜欢模拟/覆盖你的过程调用。 但是when过程期望你的请求对象是mockito框架中的模拟对象。
即使你创建了一个模拟的ServletRequest对象,但这不是Mockito的模拟对象。
看看mockito开始页面; 有一个例子: https : //code.google.com/p/mockito/在第一个代码块/示例中查看第二行; 有一个模拟对象创建如下:
List mockedList = mock(List.class);
意味着您需要像这样创建请求对象(而不是使用new-operator):
MockHttpServletRequest request = mock(MockHttpServletRequest.class);
希望这有助于解决您的问题。