How to test a spring mvc controller

爱⌒轻易说出口 提交于 2021-02-16 15:07:45

问题


I have the following controller:

@Controller
public class HomeController {
    @Resource(name="returnGraph")
    Graph returnGraph;

    @RequestMapping("/")
    public String goToHomePage(HttpSession session){
        session.setAttribute("sm", returnGraph.getVertexes());
        return "home";
    }
}

I tried the following j unit test but it didnt work:

public class HomeControllerTest {

    @Mock
    Graph returnGraph;
    @Mock
    Map<String,Vertex> vertexes;
    @Mock
    HttpSession session;

    HomeController homeController;

    @Before
    public void setUp() {
        MockitoAnnotations.initMocks(this);
        homeController = new HomeController();
    }

    @Test
    public void testgoToHomePage(){
        when(returnGraph.getVertexes()).thenReturn(vertexes);
        assertEquals("home", homeController.goToHomePage(session));
    }
}

It says I have null pointer exception at.

session.setAttribute("sm", returnGraph.getVertexes());

However I am not sure why? I am not sure what more I can do about this, how exactly do I deal with the session.setAttribute.


回答1:


You may try the Spring MVC Test Framework, here is the documatation:

http://docs.spring.io/spring-framework/docs/3.2.0.BUILD-SNAPSHOT/reference/htmlsingle/#spring-mvc-test-framework

You can test your controller like this:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
public abstract class HomeControllerTest {

    @Autowired
    protected WebApplicationContext context;

    @Resource(name="returnGraph")
    Graph returnGraph;

    protected MockMvc mockMvc;

    @Test
    public void testgoToHomePage(){
        this.mockMvc.perform(get("/")
           .andExpect(status().isOk())
           .andExpect(content().string("home"));
    }

}



回答2:


@RunWith(SpringJUnit4ClassRunner.class)
public class HomeControllerTest {

@Mock
Graph returnGraph;

@Mock
Map<String,Vertex> vertexes;

@Mock
HttpSession session;

@InjectMocks
HomeController homeController;

@Before
public void setUp() {
    MockitoAnnotations.initMocks(this);


}

@Test
public void testgoToHomePage(){
    when(returnGraph.getVertexes()).thenReturn(vertexes);
    assertEquals("home", homeController.goToHomePage(session));
}

}



回答3:


You have to use these annotations: @RunWith(SpringJUnit4ClassRunner.class), @WebAppConfiguration

If using JavaConfig: @ContextConfiguration(classes = MyWebConfig.class)

A complete working example : http://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/spring-mvc-unit-testing/



来源:https://stackoverflow.com/questions/36273195/how-to-test-a-spring-mvc-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!