2011-05-11 119 views
1

Spring MVC新增功能,我使用Spring MVC和resteasy編寫了web servise。我的控制器工作正常,現在需要編寫測試用例,但我試過寫作,但我從來沒有成功自動裝配問題。Spring MVC測試用例

@Controller

@Path("/searchapi") 
public class SearchAPIController implements ISearchAPIController { 
@Autowired 
    private ISearchAPIService srchapiservice; 
@GET 
    @Path("/{domain}/{group}/search") 
    @Produces({"application/xml", "application/json"}) 
    public Collections getSolrData(
      @PathParam("domain") final String domain, 
      @PathParam("group") final String group, 
      @Context final UriInfo uriinfo) throws Exception {  
     System.out.println("LANDED IN get****************"); 
     return srchapiservice.getData(domain, group, uriinfo); 
    } 
}

誰能給我示例代碼Spring MVC中的測試用例。

回答

3

「春-MVC」測試案例似乎可以這樣使用模擬對象,比如我們想測試我MyControllerToBeTest:

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration("/spring.xml") 
public class MyControllerTest { 

    private MockHttpServletRequest request; 
    private MockHttpServletResponse response; 
    private MyControllerToBeTested controller; 
    private AnnotationMethodHandlerAdapter adapter; 

    @Autowired 
    private ApplicationContext applicationContext; 

    @Before 
    public void setUp() { 
     request = new MockHttpServletRequest(); 
     response = new MockHttpServletResponse(); 
     response.setOutputStreamAccessAllowed(true); 
     controller = new MyControllerToBeTested(); 
     adapter = new AnnotationMethodHandlerAdapter(); 
    } 

    @Test 
    public void findRelatedVideosTest() throws Exception { 
     request.setRequestURI("/mypath"); 
     request.setMethod("GET"); 
     request.addParameter("myParam", "myValue"); 
     adapter.handle(request, response, controller); 
     System.out.println(response.getContentAsString()); 
    } 

} 

,但我沒有與REST資源測試的經驗,在你的情況下RestEasy。

+0

在http://www.scarba05.co.uk/blog/2010/03/integration-testing-of-springs-mvc-annotation-mapppings-for-controllers/中描述了類似的解決方案 – ilcavero 2011-08-19 18:12:25

0

如果你想測試容器內的全部服務,你可以看看REST Assured框架的Java。它使測試和驗證基於HTTP/REST的服務變得非常簡單。