You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

向Mock Server发送POST请求时Karate测试报Broken pipe错误

Karate测试调用自身Mock Server报Broken pipe错误,Postman请求正常

问题现象

运行Karate测试套件,向本地部署在http://localhost:8080/api/messages的Karate Mock Server发送POST请求时,抛出如下错误:

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"}'

Karate测试代码

发送SMS的测试feature文件:

@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

Mock Server详情

基于Karate实现的Mock Server代码:

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

Mock Server已成功启动:

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

环境信息

  • Karate版本:1.4.1
  • JDK版本:OpenJDK 21

可行解决方法

  1. 补全请求头:Postman请求包含Content-Type: application/json,但Karate测试仅设置了Accept头,添加该头后重试:
Background:
  * header Accept = 'application/json'
  * header Content-Type = 'application/json'
  1. 调整HTTP客户端配置:在测试中添加配置,禁用连接复用或延长超时时间:
Scenario: Send an SMS
  * configure httpClient = { connectTimeout: 5000, socketTimeout: 5000, connectionReuse: false }
  Given url 'http://localhost:8080/api/messages'
  # 其余代码不变
  1. 修改Mock Server线程模型:Karate Mock Server默认单线程处理请求,若测试并发执行可能导致连接问题,可启用多线程:
// 启动Mock Server时添加线程池配置
MockServer server = MockServer.feature("classpath:mock/sms-mock.feature").http(8080).threadPool(5).start();
  1. 降级JDK版本:OpenJDK 21与Karate 1.4.1可能存在兼容性问题,尝试切换到JDK 17或11测试。

内容的提问来源于stack exchange,提问作者Mark Hughes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 18:22:42