gpt4 book ai didi

java - 编写 JUnit 测试用例请求调度程序时出错

转载 作者:行者123 更新时间:2023-12-03 19:23:30 24 4
gpt4 key购买 nike

我在为请求调度程序编写测试用例时遇到了一些错误。我的类(class)

@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();

这里有两种“模拟”意义:

  1. Mockito 提供的模拟是基于接口(interface)自动生成的,并使用 whenverify 等静态方法进行操作。 Mockito 模拟是使用 Mockito.mock(或 @Mock 当且仅当您使用 MockitoJUnitRunnerMockitoAnnotations.initMocks).

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

例如,FilterChain 可能会由 Mockito 提供。 MockHttpServletRequest 请求 不是 Mockito 模拟,这就是您收到错误消息的原因。

您最好的选择是选择一种模拟类型或另一种类型——两者都可以——并确保您使用 when 语句(如果您选择 Mockito)或 setter ,如 setRequestURI(如果您选择 MockHttpSession 样式的模拟)。

关于java - 编写 JUnit 测试用例请求调度程序时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22357046/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com