基于 Node.js 与 Testosterone 的轻量级接口测试方案

作者:星河时间:2026-10-27 15:58:57浏览:105

针对 Java 编写功能测试代码冗余的问题,本文介绍使用 Node.js 结合 Testosterone 库构建轻量级接口测试模板。通过 Express 搭建模拟服务器,利用 Testosterone 提供的简洁 API 进行 GET/POST 请求验证,并展示如何结合 Given-When-Then 模式提升测试用例的可读性与维护性。

背景与选型

在上周的会议中,同事反馈目前使用 Java 编写功能测试(Function Test)产生了大量冗余代码,导致项目结构臃肿。团队急需一个简洁的模板项目,以便快速搭建功能测试环境。

随后我深入思考,为何必须依赖 Java 来执行功能测试?

Node.js 凭借其原生支持 JSON 的特性,成为更优的选择。我在 GitHub 上搜索后发现了 testosterone 项目,并据此撰写了本文。

服务端搭建

为了演示 Demo,我们需要搭建相应的服务端支持。

此处选择 Express 作为后端服务器框架。

首先创建 server 文件夹,并初始化 package.json 文件。

配置内容如下:

{
"name": "wine-cellar",
"description": "Wine Cellar Application",
"version": "0.0.1",
"private": true,
"dependencies": {
"express": "3.x"
    }
}

接下来执行安装命令。

命令如下:

npm install

执行后即可安装 Express 依赖。

我们实现几个简单的 GET 和 POST 方法用于实验。

服务器代码示例如下:

var express = require('express')
, app = express();
app.use(express.bodyParser());
app.get('/hello', function(req, res) {
 res.send("hello world");
});
app.get('/', function (req, res) {
 setTimeout(function () {
 res.writeHead(200, {'Content-Type': 'text/plain'});
 res.end();
 }, 200);
});
app.get('/hi', function (req, res) {
 if (req.param('hello') !== undefined) {
 res.writeHead(200, {'Content-Type': 'text/plain'});
 res.end('Hello!');
 } else {
 res.writeHead(500, {'Content-Type': 'text/plain'});
 res.end('use post instead');
 }
});
app.post('/hi', function (req, res) {
 setTimeout(function () {
 res.writeHead(200, {'Content-Type': 'text/plain'});
 res.end(req.param('message') || 'message');
 }, 100);
});
app.get('/user', function(req, res) {
 res.send(
 [
 {name:'jack'}, 
 {name:'tom'}
 ]
 );
});
app.get('/user/:id', function(req, res) {
 res.send({
 id: 1, 
 name: "node js", 
 description: "I am node js"
 });
});
app.post('/user/edit', function (req, res) {
 setTimeout(function () {
 res.send({
 id:req.param('id'),
 status:1
 });
 }, 100);
}); 
app.listen(3000);
console.log('Listening on port 3000...');

接口测试实现

testosterone 服务器搭建完成后,开始进行测试环节。

该项目的接口命名规范且优雅,直接展示代码。

首先测试基本功能。

代码如下:

var testosterone = require('testosterone')({port: 3000})
, assert = testosterone.assert;
testosterone
 .get('/hello',function(res){
 assert.equal(res.statusCode, 200);
 })
.get('/hi',function(res){
 assert.equal(res.statusCode, 500);
 })
.post('/hi', {data: {message: 'hola'}}, {
 status: 200
 ,body: 'hola'
 });

接着针对上述模拟的用户接口进行 GET 和 POST 测试。

代码示例如下:

var testosterone = require('testosterone')({port: 3000})
, assert = testosterone.assert;
testosterone 
 .get('/user', function (res) {
 var expectRes = [
 {name:'jack'}, 
 {name:'tom'}
 ];
assert.equal(res.statusCode, 200);
 assert.equal(JSON.stringify(JSON.parse(res.body)),JSON.stringify(expectRes));
 })
.get('/user/1', function (res) {
 var user = JSON.parse(res.body);
assert.equal(res.statusCode, 200);
 assert.equal(user.name, "node js");
 assert.equal(user.description,"I am node js");
 })

若希望使用 Given-When-Then 模式描述每个测试用例,可采用以下方式:

代码如下:

var testosterone = require('testosterone')({port: 3000, title: 'test user api'})
, add = testosterone.add
, assert = testosterone.assert;
testosterone
 .add(
 'GIVEN a user id to /user/{id} \n' +
 'WHEN it have response user \n' +
 'THEN it should return user json',
function (cb) {
 testosterone.get('/user/1', cb(function (res) {
 var expectRes = {
 id: 1, 
 name: "node js", 
 description: "I am node js"
 };
assert.equal(res.statusCode, 200);
 assert.equal(JSON.stringify(JSON.parse(res.body)), JSON.stringify(expectRes));
 }));
 })
.add(
 'GIVEN a POST a user info to /user/edit \n' +
 'WHEN find modify success \n' +
 'THEN it should resturn status 1',
function (cb) {
 testosterone.post('/user/edit', {data: {id: 1, name: "change name"}}, cb(function (res) {
 var res = JSON.parse(res.body);
 assert.equal(res.status, 1);
 }));
 }
 )
.run(function () {
 require('sys').print('done!');
 });

Conclusion 通过上述代码对比可见,相较于 Java 冗长的 HTTP 头设置等操作,Testosterone 在简洁性和优雅性上具有明显优势。

作者最新文章