在Linux上利用Swagger實現API自動化測試,可以按照以下步驟進行:
首先,需要在Linux系統上安裝Node.js和npm??梢酝ㄟ^以下命令安裝:
curl -sL https://deb.nodesource.com/setup_14.x | sudo -E bash -
sudo apt-get install -y nodejs
可以使用npm全局安裝Swagger Editor:
npm install -g http-server
然后,下載并解壓Swagger Editor:
wget https://github.com/swagger-api/swagger-editor/archive/refs/tags/v3.16.1.tar.gz
tar -xvf v3.16.1.tar.gz
cd swagger-editor-3.16.1
./node_modules/.bin/http-server -p 8080
訪問http://localhost:8080
即可使用Swagger Editor。
同樣,可以通過npm安裝Swagger UI:
npm install -g swagger-ui
然后,下載并解壓Swagger UI:
wget https://github.com/swagger-api/swagger-ui/archive/refs/tags/v3.48.0.tar.gz
tar -xvf v3.48.0.tar.gz
cd swagger-ui-3.48.0
./node_modules/.bin/http-server -p 8081
訪問http://localhost:8081
即可使用Swagger UI。
在項目目錄下,添加Swagger配置文件(通常是swagger.yaml
或swagger.json
),并配置API的基本信息、端點、參數、請求和響應等。
配置完成后,通過命令行啟動Swagger,啟動后會在瀏覽器中打開一個界面,顯示你的API文檔。
在Controller類的方法上添加Swagger注解,例如@ApiOperation
和@ApiResponses
,以生成API文檔。
可以使用Postman、cURL等工具,或者編寫自動化測試腳本。例如,使用Python的requests
庫編寫自動化測試腳本:
import requests
def test_api():
response = requests.get('http://localhost:8080/api/users')
assert response.status_code == 200
test_api()
可以將Swagger Editor和Swagger UI容器化部署,實現遠程訪問和團隊協作編輯:
docker pull swaggerapi/swagger-editor
docker run -p 8080:8080 -p 8081:8081 swaggerapi/swagger-editor
訪問http://localhost:8080
和http://localhost:8081
即可使用Swagger Editor和Swagger UI。
通過以上步驟,可以在Linux上利用Swagger實現API自動化測試,提高開發和測試效率。