如何测试弹簧mvc控制器

时间:2016-03-28 23:58:29

标签: java spring junit mockito

我有以下控制器:

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

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

我尝试了以下j单元测试,但它没有用:

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

它说我在。

处有空指针异常
session.setAttribute("sm", returnGraph.getVertexes());

但是我不确定为什么?我不知道我还能做些什么,我究竟如何处理session.setAttribute。

3 个答案:

答案 0 :(得分:1)

您可以尝试使用Spring MVC测试框架,这里是文档:

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

您可以像这样测试您的控制器:

@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"));
    }

}

答案 1 :(得分:0)

@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));
}

}

答案 2 :(得分:0)

您必须使用这些注释:@RunWith(SpringJUnit4ClassRunner.class)@WebAppConfiguration

如果使用JavaConfig:@ContextConfiguration(classes = MyWebConfig.class)

一个完整的工作示例:http://www.logicbig.com/tutorials/spring-framework/spring-web-mvc/spring-mvc-unit-testing/