How to unit test a Spring MVC annotated controller?

后端 未结 3 1337
陌清茗
陌清茗 2020-12-24 03:41

I am following a Spring 2.5 tutorial and trying, at the same time, updating the code/setup to Spring 3.0.

In Spring 2.5 I had the HelloControlle

3条回答
  •  暖寄归人
    2020-12-24 04:18

    One advantage of annotation-based Spring MVC is that they can be tested in a straightforward manner, like so:

    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());
           ...
       }
    }
    

    Is there any problem with this approach?

    For more advanced integration testing, there is a reference in Spring documentation to the org.springframework.mock.web.

提交回复
热议问题