【问题标题】:Testing Spring Controllers with JUnit使用 JUnit 测试 Spring 控制器
【发布时间】:2012-08-08 11:42:36
【问题描述】:

如何在 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() {

    }

}

【问题讨论】:

    标签: java spring google-app-engine junit


    【解决方案1】:

    如果您有一个测试服务器启动并运行, 尝试在您的测试方法中使用 Spring RestTemplate

    类似:

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

    查看更多here

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

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

    【讨论】:

    • 我确实使用了 Google Http Client 而不是 RestTemplate,因为我似乎无法使其与 App Engine 一起使用
    猜你喜欢
    • 1970-01-01
    • 2014-12-01
    • 1970-01-01
    • 2021-07-23
    • 2020-05-29
    • 1970-01-01
    • 2018-03-14
    • 1970-01-01
    • 2013-02-19
    相关资源
    最近更新 更多