简体   繁体   English

使用JUnit测试Spring控制器

[英]Testing Spring Controllers with JUnit

How do I test a "resource" in a Spring Controller: 如何在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);
}

And since I am developing with App Engine I have a JUnit scaffolding like this: 因为我正在使用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() {

    }

}

If you have a test server up and running, try using Spring RestTemplate in your test method 如果您已启动并运行测试服务器,请尝试在测试方法中使用Spring RestTemplate

something like: 就像是:

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

See more here . 在这里查看更多。

If you don't have a server and need basic unit testing, try mocking one. 如果您没有服务器并且需要基本的单元测试,请尝试模拟一个。 More info on another stackoverflow question . 有关另一个stackoverflow问题的更多信息。

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

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

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