gpt4 book ai didi

java - 如何对 Spring MVC 注释 Controller 进行单元测试?

转载 作者:IT老高 更新时间:2023-10-28 13:49:48 28 4
gpt4 key购买 nike

我正在关注 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 documentationorg.springframework.mock.web .

关于java - 如何对 Spring MVC 注释 Controller 进行单元测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5774349/

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