如何测试springmvc控制器



我有以下控制器:

@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.

您可以尝试Spring MVC测试框架,这是当前的文档或归档文档

你可以这样测试你的控制器:

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

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

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

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

相关内容

  • 没有找到相关文章

最新更新