2012-08-08 124 views
1

如何在Spring控制器测试“资源”:测试弹簧控制器使用JUnit

@RequestMapping(value = "/{query}", method = RequestMethod.GET) 
public @ResponseBody String getResource(
     HttpServletRequest req, 
     HttpServletResponse res, 
     @PathVariable String query, 
     @RequestParam(value="param1", required = false) String param1, 
     @RequestParam(value="param2", required = false) String param2) throws SomeException{ 
    return service.read(query); 
} 

而且,因为我与App Engine开发我有一个JUnit脚手架像这样:

@ContextConfiguration(locations = { "classpath:service/client-config.xml" }) 
@RunWith(SpringJUnit4ClassRunner.class) 
public class LocalDatastoreTest { 
    private final LocalServiceTestHelper helper = 
      new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig()); 

    @Before 
    public void setUp() { 
     helper.setUp(); 
    } 

    @After 
    public void tearDown() { 
     helper.tearDown(); 
    } 

    @Test 
    public void test() { 

    } 

} 

回答

3

如果你有一个测试服务器正常运行, 尝试在您的测试方法使用Spring RestTemplate

类似:

RestTemplate restTemplate = new RestTemplate(); 
String result = restTemplate.getForObject("YOUR_URL/{query}", String.class,"myQuery"); 

查看更多here

如果您没有服务器并需要基本的单元测试,请尝试嘲笑之一。 另一个stackoverflow question更多信息。

,或者尝试使用https://github.com/SpringSource/spring-test-mvc

+0

我没有使用谷歌的HTTP客户端,而不是作为RestTemplate我似乎无法让它使用App Engine – xybrek 2012-08-08 19:25:45