繁体   English   中英

使用JUnit测试Spring控制器

[英]Testing Spring Controllers with JUnit

如何在Spring Controller中测试“资源”:

@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() {

    }

}

如果您已启动并运行测试服务器,请尝试在测试方法中使用Spring RestTemplate

就像是:

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

在这里查看更多。

如果您没有服务器并且需要基本的单元测试,请尝试模拟一个。 有关另一个stackoverflow问题的更多信息。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM