gpt4 book ai didi

java - Mockito servlet 测试 : cannot use response - it's not committed

转载 作者:搜寻专家 更新时间:2023-10-31 08:11:53 25 4
gpt4 key购买 nike

我已经对 servlet 进行了基本测试以测试它的响应状态代码,但它不起作用 - 它始终为 0,尽管我已将 servlet 中的响应状态代码设置为 200。

public class TestMyServlet extends Mockito {

@Test
public void test() throws Exception {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);

when(request.getParameter("test")).thenReturn("1");

new MyServlet().doPost(request, response);

System.out.println(response.isCommited()); // false
System.out.println(response.getContentType()); // null
System.out.println(response.getStatus()); // 0
}
}

如何让它发挥作用?

最佳答案

您想以不同的方式进行测试。您需要验证您的输入导致预期输出。对于非模拟结果,您可以断言该行为。因为您想验证您的输出设置是否正确。

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;

public class MyServletTests {
@Test
public void testValidRequest() throws Exception {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);

when(request.getParameter("test")).thenReturn("1");

new MyServlet().doPost(request, response);

// ensure that the request was used as expected
verify(request).getParameter("test");

// ensure that the response was setup as expected based on the
// mocked inputs
verify(response).setContentType("text/html");
verify(response).setStatus(200);
}
}

如果您希望某些输入不会被触及,那么您应该考虑使用 verify(response, never()).shouldNotBeCalledButSometimesIs() 来验证该行为(以验证条件何时控制它被调用/设置与不调用)。

关于java - Mockito servlet 测试 : cannot use response - it's not committed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30133388/

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