我正在关注 Spring 2.5 教程,同时尝试将代码/设置更新到 Spring 3.0。
在 Spring 2.5 我有 HelloController(供引用):
public class HelloController implements Controller {
protected final Log logger = LogFactory.getLog(getClass());
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
logger.info("Returning hello view");
return new ModelAndView("hello.jsp");
}
}
HelloController 的 JUnit 测试(供引用):
public class HelloControllerTests extends TestCase {
public void testHandleRequestView() throws Exception{
HelloController controller = new HelloController();
ModelAndView modelAndView = controller.handleRequest(null, null);
assertEquals("hello", modelAndView.getViewName());
}
}
但现在我将 Controller 更新为 Spring 3.0,它现在使用注释(我还添加了一个 消息):
@Controller
public class HelloController {
protected final Log logger = LogFactory.getLog(getClass());
@RequestMapping("/hello")
public ModelAndView handleRequest() {
logger.info("Returning hello view");
return new ModelAndView("hello", "message", "THIS IS A MESSAGE");
}
}
知道我使用的是 JUnit 4.9,有人能解释一下如何对最后一个 Controller 进行单元测试吗?
最佳答案
基于注解的 Spring MVC 的一个优点是可以直接进行测试,如下所示:
import org.junit.Test;
import org.junit.Assert;
import org.springframework.web.servlet.ModelAndView;
public class HelloControllerTest {
@Test
public void testHelloController() {
HelloController c= new HelloController();
ModelAndView mav= c.handleRequest();
Assert.assertEquals("hello", mav.getViewName());
...
}
}
这种方法有什么问题吗?
对于更高级的集成测试,有 reference in Spring documentation到org.springframework.mock.web .
关于java - 如何对 Spring MVC 注释 Controller 进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5774349/