如何在 spock 中为 Rest Service API 编写集成测试

我有一个包含 API 方法的 Java 类


前任:


@GET

@Path("/{id}")

public Resposce getIds(@PathParam(name) String name) {

     //some code here 

}

我想对此 API 进行正确的集成测试,即在测试时我想使用path但不使用方法名称调用此方法


qq_笑_17
浏览 243回答 2
2回答

智慧大石

这对我有用import com.charter.aesd.testcommons.RESTSpecificationimport groovyx.net.http.HttpResponseDecoratorclass TestIT extends RESTSpecification{&nbsp; &nbsp; def BASE_URL = "/test"&nbsp; &nbsp; def "Get test"(){&nbsp; &nbsp; &nbsp; &nbsp; when:&nbsp; &nbsp; &nbsp; &nbsp; HttpResponseDecorator response = getRestClient().get([path:"$BASE_URL"+"/123"])&nbsp; &nbsp; &nbsp; &nbsp; then:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; response.status >=200 && response.status < 400&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; String getBaseUrl() {&nbsp; &nbsp; &nbsp; &nbsp; return 'http://localhost:8889/'&nbsp; &nbsp; }}

扬帆大鱼

正如您明确要求 Spock:这是我的标准实现ApiSpec:@SpringBootTest(webEnvironment = RANDOM_PORT)abstract class AbstractServiceSpec extends Specification {&nbsp; &nbsp; protected final static RestTestClient api = new RestTestClient()&nbsp; &nbsp; @Value('http://localhost:${local.server.port}')&nbsp; &nbsp; String serviceUrl&nbsp; &nbsp; def setup() {&nbsp; &nbsp; &nbsp; &nbsp; api.baseUrl = serviceUrl&nbsp; &nbsp; }&nbsp; &nbsp; def "GET /health should return 200"() {&nbsp; &nbsp; &nbsp; &nbsp; expect:&nbsp; &nbsp; &nbsp; &nbsp; api.get("/health").code() == 200&nbsp; &nbsp; }}请注意,这RestTestClient是我自己的 OkHttp 包装器。当然,您可以使用手头的任何 HTTP 客户端。该@SpringBootTest注解使得春季启动的全程服务。在执行测试时,服务已完全启动并运行,您可以对 API 进行黑盒测试。通常测试 Web 层是一个很好的读物,其中大部分——正如你在示例中看到的——可以在 Spock 和 JUnit 中完成。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python