public void testInvokesCorrectMethodWithSession() throws Exception {
TestController cont = new TestController();
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/invoiceView.app");
request.setSession(new MockHttpSession(null));
HttpServletResponse response = new MockHttpServletResponse();
ModelAndView mv = cont.handleRequest(request, response);
assertTrue("Invoked loggedIn method", cont.wasInvoked("loggedIn"));
assertTrue("view name is ",mv.getViewName().equals("loggedIn"));
assertTrue("Only one method invoked", cont.getInvokedMethods() == 1);//测试控制器但是不使用会话
request = new MockHttpServletRequest("GET", "/invoiceView.app");
response = new MockHttpServletResponse();
try {
cont.handleRequest(request, response);
fail("Should have rejected request without session");
} catch (ServletException ex) {//在此加入期盼的异常处理}}
(三)转发和重定向
一个Spring MVC组件执行的操作能够导致转发或重定向到另一个URL。如果你的目标是分析转发或重定向的结果,那么你可以测试这一情形—通过分析MockHttpResponse对象并进而确定有哪些内容包含在它的重定向或转发值中,如下所示:
String responseString = ((MockHttpServletResponse)httpResponse).getForwardedUrl();
assertEquals( "Did not forward to the expected URL", responseString, expectedString);
四、生成正确的二进制输出
如何确定你有多少次必须实现“View as PDF”这一功能?下面的JUnit代码片断使用mock输出流对象实现这一功能的正确测试:
public void testPDFGeneration() throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
文章来源于领测软件测试网 https://www.ltesting.net/