如何在Ballerina中对HTTP服务进行单元测试



假设我有一个用Ballerina编写的echoHTTP服务,如下所示:

import ballerina/http;
service / on new http:Listener(9090) {
resource function post echo(@http:Payload json payload) returns json {
return payload;
}
}

如何编写单元测试echo资源方法的行为?

您可以使用Ballerina HTTP客户端为HTTP服务编写单元测试。

将测试放在Ballerina项目的tests目录中。

以下是一个示例测试:

import ballerina/http;
import ballerina/test;
@test:Config {}
function testService() returns error? {
http:Client httpClient = check new("http://localhost:9090");
json requestPayload = {message: "hello"};
http:Request request = new;
request.setPayload(requestPayload);
json responsePayload = check httpClient->post("/echo", request);
test:assertEquals(responsePayload, requestPayload);
}

在这里,我们发送一个有效负载并使用HTTP客户端将其取回,然后检查echo服务是否发送回相同的有效负载。

运行测试时,服务将自动启动。您不必手动运行它们。

最新更新