2015-02-23 99 views
1

我有春天工具套件IDE中創建簡單的Spring MVC的項目,所以項目的結構如何測試spring RESTful MVC控制器方法?

enter image description here

我需要測試我控制器的方法,例如

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

服務器是接口,它具有實現(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(); 
     }  
    } 

} 

我如何測試我的控制器,該項目結構? 謝謝。

+0

有問題嗎? – Tony 2015-02-23 14:33:15

+0

現在,謝謝你的評論。 – 2015-02-23 14:40:47

+0

單元測試的方法?或者測試Spring註釋?或兩者? – Raedwald 2017-11-10 17:06:34

回答

0

通過使用我們可以測試彈簧安置/彈簧WS應用程序的org.springframework.web.client.RestTemplate。

sample code

0

嘗試下面的代碼片段上設置

@Before 公共無效設置($ basecontroller controllerobj)
{this.mockMvc = MockMvcBuilders.standAloneSetup(controllerobj).dispatchOptions(真)。建立(); }

$ basecontroller =與其他控制器駐留在同一個包中的控制器的基礎控制器。

相關問題