通过JUnit运行Karate特性文件时Spring Boot接口测试请求失败如何解决
Spring Boot整合Karate测试配置错误修复说明
- 问题1:
@SpringBootTest未配置启动真实Web服务
默认@SpringBootTest使用webEnvironment = WebEnvironment.MOCK模式,仅创建模拟Web上下文,不会启动监听端口的Servlet容器,因此8443端口无服务响应,导致Karate请求失败。
修复方式:修改@SpringBootTest注解配置,指定启动真实Web服务,推荐使用随机端口避免端口冲突:
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
如果确实需要使用固定的8443端口,可改为webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT,同时确认项目SSL配置正确加载。
- 问题2:未将动态端口传递给Karate
使用随机端口时,Spring Boot启动的端口是动态生成的,不能硬编码在feature文件中。需要通过@LocalServerPort注解读取实际启动端口,再传递给Karate作为全局参数。
修改后的完整测试类代码如下:
package com.example.controller; import com.intuit.karate.junit5.Karate; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.web.server.LocalServerPort; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class ControllerTest { @LocalServerPort private int port; @Karate.Test Karate testSample() { return Karate.run("sample") .relativeTo(getClass()) .systemProperty("server.port", String.valueOf(port)); } }
- 问题3:Feature文件语法顺序错误,存在硬编码配置
现有feature文件中先声明path再声明url不符合Karate语法规范,且硬编码的地址适配性差。修改后的feature文件内容如下:
Feature: sample Scenario: Test Create Given url 'http://localhost:' + #(server.port) And path '/test' When method GET Then status 200
如果你的项目配置了HTTPS,将url中的http改为https即可。
内容的提问来源于stack exchange,提问作者Yash Patil
相关产品推荐
相关产品推荐

