zoukankan      html  css  js  c++  java
  • 使用 Node.js 做 Function Test

    Info

    上周 meeting 上同事说他们现在在用 java 写 function test,产生了很多冗余的代码,整个项目也变得比较臃肿。现在迫切需要个简单的模板项目能快速搭建function test。

    后来我回去想了想,为什么我们非得用 java 来做 function test 呢?

    Node.js 应该是个不错的选择,并且对 json 有着天然的支持,于是回去在 github 上随手一搜,还果真有相关的项目:testosterone,于是便有了这篇blog.

    Server

    要做demo,自然要有相应的server来支撑。

    在这里我们选用Express作为server。

    首先我们建立一个server的文件夹,新建package.json。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    {
        "name": "wine-cellar",
        "description": "Wine Cellar Application",
        "version": "0.0.1",
        "private": true,
        "dependencies": {
            "express": "3.x"
        }
    }
    

    接下来run command

    1
    
    npm install
    

    这样express就装上了。

    我们实现几个简单的 get post 方法来做实验

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    
    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

    server 架设完毕,自然要开始做测试了。

    这个 project 的接口的命名都挺优雅,直接上代码。

    首先是测试基本的功能

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    
    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'
      });
    

    然后针对上面模拟的user的get post 做简单的测试。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    
    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");
      })
    

    接下来,如果你想要针对每个test case 用 give when then 来描述的话,可以这样:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    
    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}  
    ' +
        'WHEN it have response user 
    ' +
        '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 
    ' +
        'WHEN find modify success 
    ' +
        '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确实简单和优雅了不少。

    testosterone 是个蛮不错的项目,作者写的文档简单易懂,在 test 文件夹里面也有很多测试代码。

    本篇 blog 的 sample code 的放在 https://github.com/nateriver520/function-test-demo

  • 相关阅读:
    Gradle在大型Java项目上的应用
    Spring MVC 构建入门级 Web 应用程序
    大公司最喜欢问的Java集合类面试题
    在Java中正确使用注释
    Java的wait(), notify()和notifyAll()使用心得
    Java中HashMap和TreeMap的区别深入理解
    初识PGM图片
    VS2013报错 error MSB8031解决方法
    matconvnet在MATLAB2013配置过程中遇到的问题
    配置VLFeat-0.9.20+MATLAB2013a
  • 原文地址:https://www.cnblogs.com/nateriver520/p/3378078.html
Copyright © 2011-2022 走看看