快速开始

编写并运行你的第一个 Test::Nginx 测试用例

第一个测试

创建文件 t/001-hello.t,这是一个最简单的测试用例:

perl
1# t/001-hello.t
2use Test::Nginx::Socket 'no_plan';
3
4run_tests();
5
6__DATA__
7
8=== TEST 1: hello world
9--- config
10 location /hello {
11 return 200 "Hello, Test::Nginx!";
12 }
13--- request
14GET /hello
15--- response_body
16Hello, Test::Nginx!
17--- error_code: 200

结构解析

一个测试文件由两部分组成:

Prologue(序言)__DATA__ 之前的 Perl 代码

  • use Test::Nginx::Socket - 加载测试模块
  • run_tests() - 告知框架执行测试

Data 段__DATA__ 之后的测试块

  • === TEST 1: hello world - 测试块标题
  • --- config - Nginx 配置段
  • --- request - HTTP 请求
  • --- response_body - 预期响应体
  • --- error_code - 预期 HTTP 状态码

运行测试

使用 prove 命令运行测试:

bash
1# 运行单个测试文件
2prove -v t/001-hello.t
3
4# 运行 t/ 目录下所有测试
5prove -v -r t/
6
7# 以详细模式运行(推荐调试时使用)
8prove -v t/001-hello.t 2>&1 | less

确保系统中已安装 Nginx 并且在 PATH 中可用,或通过 TEST_NGINX_BINARY 环境变量指定 Nginx 路径。

预期输出

成功运行后你会看到类似这样的输出:

text
1t/001-hello.t ..
2ok 1 - TEST 1: hello world - status code ok
3ok 2 - TEST 1: hello world - response_body - response is expected (Hello, Test::Nginx!)
41..2
5ok
6All tests successful.
7Files=1, Tests=2, 1 wallclock secs (...)
8Result: PASS