如何测试spring RESTful MVC控制器方法?

时间:2015-02-23 14:30:37

标签: java spring spring-mvc

我在Spring Tool Suite IDE中创建了简单的Spring MVC项目,因此项目的结构是

enter image description here

我需要测试我的控制器方法,例如

    @RequestMapping(value = "/references/{id}", method = RequestMethod.GET)
    public @ResponseBody GAReference getReference(@PathVariable("id") int id) { 
        return server.getReference(id);
    }

server是一个接口,它有实现(ServerTestImpl),并且在MainControllerContext.xml中存储了一个ServerTestImpl bean。

我希望我的测试类看起来像这个answer,但我的项目结构中没有springDispatcher-servlet.xml。 所以,我认为它可能就像

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:/MainControllerContext.xml")
@WebAppConfiguration
public class MainControllerTest {

    private MockMvc mockMvc ;

    @Autowired
    WebApplicationContext wac;

    @Autowired
    private ServerTestImpl server;

    @Before
    public void setUp() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).dispatchOptions(true).build();
    }


    @Test
    public void testGetReference() {    
         try {
            mockMvc.perform(get("/references/5"))
            .andExpect(status().isOk())
            .andExpect(jsonPath("$", hasSize(2)))
            .andExpect(jsonPath("$[0].id", is(1)))
            .andExpect(jsonPath("$[0].description", is("Lorem ipsum")))
            .andExpect(jsonPath("$[0].title", is("Foo")))
            .andExpect(jsonPath("$[1].id", is(2)))
            .andExpect(jsonPath("$[1].description", is("Lorem ipsum")))
            .andExpect(jsonPath("$[1].title", is("Bar")));      
        } catch (Exception e) {
            e.printStackTrace();
        }       
    }

}

如何使用此项目结构测试我的控制器? 感谢。

2 个答案:

答案 0 :(得分:0)

通过使用org.springframework.web.client.RestTemplate,我们可以测试spring rest / spring-ws应用程序。

sample code

答案 1 :(得分:0)

在设置

上尝试以下代码段
  

@Before       public void setUp($ basecontroller controllerobj)
  {this.mockMvc = MockMvcBuilders.standAloneSetup(controllerobj).dispatchOptions(true).build();   }

$ basecontroller =控制器的基本控制器与其他控制器位于同一个包中。