我特别对单元测试和TDD相对较新,并准备使用mocha和chai开始我的TDD第一个项目。
我应该测试方法的存在和参数长度吗? 如果是这样,有没有比现在更好的方式呢?它感觉极端冗长,特别是在我的大多数课程中都重复这一点。
为了理解我已经设置了一些虚拟测试。
test/index.js
'use strict';
const assert = require('chai').assert;
const Test = require('../lib/index.js');
describe('Test', function() {
it('should be a function without parameters', function() {
assert.isFunction(Test);
assert.lengthOf(Test, 0);
});
let test;
beforeEach(function() {
test = new Test();
});
describe('static#method1', function() {
it('should have static method method1 with 1 parameter', function() {
assert.property(Test, 'method1');
assert.isFunction(Test.method1);
assert.lengthOf(Test.method1, 1);
});
it('should assert on non-string parameters', function() {
const params = [
123,
{},
[],
function() {}
];
params.forEach(function(param) {
assert.throws(function() {
Test.method1(param)
});
});
});
it('should return "some value"', function() {
assert.equal(Test.method1('param'), 'some value')
});
});
describe('method2', function() {
it('should have method method2 with 2 parameters', function() {
assert.property(test, 'method2');
assert.isFunction(test.method2);
assert.lengthOf(test.method2, 2);
});
it('should assert on non-number parameters', function() {
const params = [
'some string',
{},
[],
function() {}
];
params.forEach(function(param) {
assert.throws(function() {
test.method2(param)
});
});
});
it('should add the parameters', function() {
assert.equal(test.method2(1, 2), 3);
assert.equal(test.method2(9, -2), 7);
assert.equal(test.method2(3, -12), -9);
assert.equal(test.method2(-7, -5), -12);
})
});
});
经过测试的实施。
lib/index.js
'use strict';
const assert = require('chai').assert;
exports = module.exports = (function() {
class Test {
static method1(param0) {
assert.typeOf(param0, 'string');
return 'some value';
}
method2(param0, param1) {
assert.typeOf(param0, 'number');
assert.typeOf(param1, 'number');
return param0 + param1;
}
}
return Test;
}());
答案 0 :(得分:-1)
不,这样的详细测试不是必需的。它们的价值是什么?他们可以帮助您实现什么?
通常,在测试功能时,我们会测试功能的行为,而不是功能的实现。实现可以完全改变,而无需更改可观察到的行为:例如,您可以找到更可读的方法来重写代码或提高性能。
您可以通过整个测试集间接地测试函数的调用签名。每个测试都提供了有关如何使用函数的示例,从而确保其调用签名和返回参数。