2014-03-12 56 views
1

我在为请求调度程序编写测试用例时遇到了一些错误。 我班编写JUnit测试用例请求调度程序时出错

@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'. 

有人能告诉我写这篇测试案例的具体方式。

+0

MockHttpXxx类不是Mockito嘲笑。它们是实现servlet接口的简单POJO,但可以通过setter进行配置。模拟请求将返回一个模拟调度器AFAIK。而且你在测试中并没有使用调度程序,所以你可以删除该行。 –

回答

3

我没有足够的信息告诉你“写这个测试用例的确切方式”,并且StackOverflow不是一个修复大块代码的好地方,但我可以告诉你为什么得到那个消息。 :)

MockHttpServletRequest request = new MockHttpServletRequest(); 

有“模拟”这里发生的两种意义:是自动生成基于接口

  1. 的Mockito提供的模拟考试,并与像whenverify静态方法被操纵。 Mockito嘲笑使用Mockito.mock(或@Mock当且仅当您使用MockitoJUnitRunnerMockitoAnnotations.initMocks)创建。

  2. 名称以“Mock”开头的完整类,如MockHttpServletRequest,实际上是整个类的实现,它们比实际通过J2EE实现的实现更容易发生变异或更改。这些可能更准确地被称为“假”,因为它们是用于测试的简单接口实现,不验证行为并且不通过Mockito工作。你可以确定他们不是Mockito mock,因为你用new MockHttpServletRequest();实例化它们。

例如,FilterChain很可能由Mockito提供。 MockHttpServletRequest request不是Mockito模拟,这就是为什么你会收到错误信息。

最好的办法是选择一个类型的模拟或其他 - 要么将工作,并确保你正确地准备那些嘲笑与when声明(如果您选择的Mockito)或类似setRequestURI制定者(如果您选择MockHttpSession风格的嘲笑)。

1

这看起来像你正在使用Mockito来做你的单元测试。

由于该消息告诉你做一个“when(...)”你喜欢模拟/覆盖你的过程调用。 但是当程序期望你的请求对象是mockito框架的模拟对象时。

即使您创建了一个模拟ServletRequest对象,但这不是Mockito的模拟对象。

看看mockito的开始页面;有一个例子:https://code.google.com/p/mockito/ 在第一个代码块/例子看看第二行;有创建一个嘲笑的对象,如:

List mockedList = mock(List.class); 

意味着你需要创建请求对象是这样的(而不是使用新的运营商):

MockHttpServletRequest request = mock(MockHttpServletRequest.class); 

希望这有助于和解决您的问题。

+0

谢谢你的回答。 – Patan