我想用不同的传入URL测试我的Servlet。我试图使用Mockito来测试是否调用了特定的函数:
package servlet;
import blabla;
@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration(locations = {"classpath:application-context-test.xml"})
public class MainServletTest extends TestCase{
@Autowired
private Categories categories;
private MockHttpServletRequest request = new MockHttpServletRequest();
@Mock
private HttpServletResponse response;
@Mock
private HttpSession session;
@Mock
private RequestDispatcher rd;
@Test
public void testCategories() throws ServletException, IOException {
// given
request.setServerName("localhost");//here I try to change incoming URL
request.setRequestURI("/test/categories");//here I try to change incoming URL
HttpServletRequest req = spy(request);//???
//when
new MainServlet().doGet(req, response);
//then
verify(req).setAttribute("categories", categories.getContainer());//here try to check if this method is called
}
}
这里我尝试更改传入的URL并检查是否为传入请求设置了特定属性。由于 req 不是 Mock 对象,而是 MockHttpServletRequest 对象 - 此代码不起作用。有什么想法吗?
答案 0 :(得分:1)
使用模拟:
// ...
@Mock
private HttpServletRequest request;
// ...
@Test
public void testCategories() throws ServletException, IOException {
// given
when(request.getServerName()).thenReturn("localhost");
when(request.getRequestURI()).thenReturn("/test/categories")
//when
new MainServlet().doGet(req, response);
//then
verify(req).setAttribute("categories", categories.getContainer());
或
使用MockHttpServletRequest
检查名为categories
的属性:
assertEquals(categories.getContainer(), req.getAttributes("categories"));