我正在运行空手道测试套件,将 POST 请求发送到在 http://localhost:8080/api/messages 上本地运行的模拟服务器。模拟服务器是使用空手道本身实现的。虽然该请求在 Postman 中完美运行,但在 Karate 中失败并出现错误:
00:06:12.347 [pool-1-thread-1] ERROR com.intuit.karate - java.net.SocketException: Broken pipe, http call failed after 165 milliseconds for url: http://localhost:8080/api/messages
00:06:12.348 [pool-1-thread-1] ERROR com.intuit.karate - classpath:resources/steps/mailosaur/send_sms.feature:12
When method POST
http call failed after 165 milliseconds for url: http://localhost:8080/api/messages
java.net.SocketException: Broken pipe
classpath:resources/steps/mailosaur/send_sms.feature:12
当通过Postman发送请求时,服务器按预期响应:
{
"success": true
}
这是来自 Postman 的等效 cURL 命令:
curl --location --request POST 'http://localhost:8080/api/messages' \
--header 'Content-Type: application/json' \
--data '{"to":"+15551234444","text":"#1234 info"}'
这是发送短信的测试功能:
@send_sms
Feature: Send SMS
Background:
* header Accept = 'application/json'
Scenario: Send an SMS
Given url 'http://localhost:8080/api/messages'
And request { "to": "+15551234444", "text": "#1234 info" }
When method POST
Then status 200
And match response.success == true
模拟服务器是在空手道中实现的:
Feature: Mock Server for SMS Testing
Background:
* def messages = []
Scenario: pathMatches('/api/messages') && methodIs('post')
* def requestBody = request
* messages.add({ to: requestBody.to, text: requestBody.text })
* def response = { success: true }
* def responseStatus = 200
模拟服务器启动成功并匹配请求:
23:57:06.953 [main] INFO com.intuit.karate - mock server initialized: src/test/java/resources/steps/mock/sms-mock.feature
23:57:07.033 [main] DEBUG com.intuit.karate.http.HttpServer - server started: mock-0082.local:8080
空手道版本:1.4.1 JDK 版本:OpenJDK 21
我认为您的模拟中有语法错误。在 JavaScript 的世界中,
push()
是如何将项目添加到数组中的。它与 Java add()
不同,后者可能会令人困惑。
进行此更改:
Scenario: pathMatches('/api/messages') && methodIs('post')
* messages.push({ to: request.to, text: request.text })
* print messages
* def response = { success: true }
* def responseStatus = 200
我无法解释为什么 Postman 可以工作,当 HTTP 服务器出现故障时,
broken pipe
可能是正常的。
为了测试,我运行了这个指向您的模拟的功能:
Feature:
Scenario:
* karate.start({ mock: 'mock.feature', port: 8080 })
Given url 'http://localhost:8080/api/messages'
And request { "to": "+15551234444", "text": "#1234 info" }
When method POST
Then status 200
And match response.success == true