温馨提示×

Linux下Swagger API测试步骤是什么

小樊
57
2025-09-20 14:04:48
栏目: 智能运维

Linux下Swagger API测试步骤

1. 安装Swagger相关工具

在Linux系统中,Swagger的测试需要依赖Swagger Editor(在线编辑与预览)、Swagger UI(可视化测试界面)和curl(命令行测试工具)。其中,Swagger Editor和Swagger UI可通过Docker快速部署:

  • 安装Docker(若未安装):
    sudo apt-get update && sudo apt-get install -y docker.io  # Debian/Ubuntu
    sudo systemctl start docker && sudo systemctl enable docker
    
  • 拉取并运行Swagger Editor(用于编写/预览API规范):
    docker pull swaggerapi/swagger-editor:v4.6.0
    docker run -d -p 38080:8080 swaggerapi/swagger-editor:v4.6.0
    
  • 拉取并运行Swagger UI(用于交互式测试):
    docker pull swaggerapi/swagger-ui:v4.15.5
    docker run -d -p 38081:8080 swaggerapi/swagger-ui:v4.15.5
    
  • 安装curl(可选,用于命令行测试):
    sudo apt-get install -y curl  # Debian/Ubuntu
    sudo dnf install -y curl      # Fedora/CentOS
    

2. 配置Swagger API规范文件

Swagger测试的核心是OpenAPI规范文件swagger.jsonswagger.yaml),需定义API的基本信息(如标题、版本)、端点路径、请求参数、响应格式等。

  • 手动创建规范文件:使用文本编辑器(如vimnano)创建swagger.yaml,示例如下:
    swagger: '2.0'
    info:
      title: Linux API测试示例
      version: 1.0.0
    paths:
      /user/query:
        get:
          summary: 根据用户ID查询信息
          parameters:
            - name: userId
              in: query
              required: true
              type: integer
          responses:
            '200':
              description: 查询成功
              schema:
                type: object
                properties:
                  id:
                    type: integer
                  name:
                    type: string
    
  • 通过代码生成规范文件(可选):若项目使用Spring Boot等框架,可添加Swagger注解(如@ApiOperation@ApiParam),然后使用swagger-maven-plugin生成规范文件:
    <!-- pom.xml添加依赖 -->
    <dependency>
      <groupId>io.springfox</groupId>
      <artifactId>springfox-swagger2</artifactId>
      <version>2.9.2</version>
    </dependency>
    

3. 导入规范文件至Swagger UI

  • 打开浏览器,访问Swagger Editor(http://localhost:38080),点击左上角File → Import File,选择步骤2中创建的swagger.yamlswagger.json文件。
  • 或直接访问Swagger UI(http://localhost:38081),在界面顶部的Swagger URL输入框中填入规范文件的本地路径(如http://localhost:38080/swagger.yaml),点击Explore导入。

4. 使用Swagger UI进行交互式测试

  • 在Swagger UI界面中,找到目标API端点(如/user/query),点击右侧的TRY IT OUT按钮。
  • 输入参数:根据接口定义填写必填参数(如userId),参数类型需与规范文件一致(如整数、字符串)。
  • 发送请求:点击Execute按钮,Swagger UI会自动向接口发送HTTP请求。
  • 查看结果:在Response区域查看接口返回的状态码(如200表示成功)、响应体(如JSON格式的用户信息)和响应头。

5. 使用curl命令进行命令行测试

若习惯使用命令行,可通过curl工具直接向接口发送请求,验证接口功能:

  • GET请求(参数在URL中)
    curl "http://your-server-ip:port/user/query?userId=123"
    
  • POST请求(参数在Body中,JSON格式)
    curl -X POST "http://your-server-ip:port/user/create" \
         -H "Content-Type: application/json" \
         -d '{"name": "John Doe", "age": 30}'
    
  • POST请求(参数在Body中,表单格式)
    curl -X POST "http://your-server-ip:port/user/login" \
         -H "Content-Type: application/x-www-form-urlencoded" \
         -d "username=admin&password=123456"
    

6. 自动化测试(可选,进阶步骤)

若需要频繁测试接口,可结合Swagger Codegen生成测试脚本,再用测试框架(如pytestJUnit)实现自动化:

  • 生成测试脚本:使用Swagger Codegen从规范文件生成客户端代码(如Java):
    java -jar swagger-codegen-cli-2.4.29.jar generate -i swagger.json -l java -o ./test-project
    
  • 编写测试用例:使用pytest编写测试脚本(test_api.py):
    import requests
    import pytest
    
    BASE_URL = "http://your-server-ip:port/api"
    
    def test_query_user():
        response = requests.get(f"{BASE_URL}/user/query?userId=123")
        assert response.status_code == 200
        assert "id" in response.json()
        assert "name" in response.json()
    
    def test_create_user():
        user_data = {"name": "Jane Doe", "age": 25}
        response = requests.post(f"{BASE_URL}/user/create", json=user_data)
        assert response.status_code == 201
        assert response.json()["name"] == "Jane Doe"
    
  • 运行测试:在终端执行pytest test_api.py,查看测试结果。

注意事项

  • 确保Docker容器正常运行,可通过docker ps查看容器状态。
  • 若Swagger UI无法访问,检查防火墙是否开放对应端口(如38081)。
  • 规范文件中的basePath需与接口实际路径一致,避免请求失败。
  • 自动化测试需结合CI/CD工具(如Jenkins),实现测试流程自动化。

0