2014-02-21 54 views
4

我正在爲外部API編寫一個API包裝器,以用於我們的應用程序。測試API包裝器

我對這個項目採用了一種測試驅動的方法,但由於我幾乎沒有編寫API包裝的經驗,我不確定我是否在正確的軌道上。

我知道我不應該測試外部API,也不應該在測試中擊中網絡。我使用Nock來模擬我對API的請求。

但是,我不確定我是否正確地做到了這一點。 /test/fixtures/authentication/error.js

我使用curl,放在一個文件(XML)的反應,例如提出了一些要求的API

module.exports = "<error>Authorization credentials failed.</error>" 

因爲我不想去訪問網絡,但要確保我的包裝器將XML解析爲JSON,我想我需要示例數據。

我的測試是這樣的:

describe("with an invalid application key", function() { 
    var cl, api; 
    before(function(done) { 
    api = nock(baseApi) 
      .get('/v1/auth/authenticate') 
      .reply(200, fixtures.authentication.error); 
    done(); 
    }); 
    after(function(done) { 
    nock.cleanAll(); 
    done(); 
    }); 
    it("returns an error", function(done) { 
    cl = new APIClient(auth.auth_user, auth.auth_pass, "abcd1234"); 
    cl.authenticate(function(err, res) { 
     should.exist(err); 
     err.should.match(/Authorization credentials failed./); 
     should.not.exist(res); 
     api.isDone().should.be.true; 
     done(); 
    }); 
    }); 
}); 

與我測試的代碼看起來像這樣:

APIClient.prototype.authenticate = function(callback) { 
    var self = this; 
    request({ 
    uri: this.httpUri + '/auth/authenticate', 
    method: 'GET', 
    headers: { 
     auth_user: this.user, 
     auth_pass: this.pass, 
     auth_appkey: this.appkey 
    } 
    }, function(err, res, body) { 
    if (err) { 
     return callback('Could not connect to the API endpoint.'); 
    } 
    self.parser.parseXML(body, function(err, result) { 
     if (err) { return callback(err); } 
     if (result.error) { return callback(result.error); } 
     self.token = result.auth.token[0]; 
     return callback(null, result); 
    }); 
    }); 
}; 

現在,這似乎對事物的認證側工作正常(我也有'success'fixture,它返回'success'XML,我檢查返回的JSON是否真的是正確的。

但是,我使用的API也有類似的端點:

/data/topicdata/realtime/:reportxhours/:topics/:mediatypes/:pageIndex/:pageSize

我不知道如何測試所有的(應該吧?)與像這些網址可能的組合。我覺得我很難在我的fixtures目錄中放入30個XML響應。另外,當嘲笑響應時,我恐怕錯過了可能的錯誤,邊緣情況等外部API可能會返回。這些有效的擔憂?

如果任何人有任何指示和/或知道任何開源和經過充分測試的API包裝我可以看看,我會非常感激。

回答

0

我認爲您的關注是非常有效的,我建議您還使用Zombie或其他基於請求的測試框架來構建測試。