3

我决定为我的下一个 javascript 项目着手 TDD,并且我正在使用 QUnit 进行单元测试。我对单元测试完全陌生,从来没有用任何语言做过。这是我的一个模块的一个示例,以及对该方法的一个测试,该find方法试图涵盖此方法将遇到的所有场景:

module("TextSwapper", {
    setup: function() { 
        this.str = 'When you first start off trying to solve a problem, the first solutions you come up with are very complex, and most people stop there. But if you keep going, and live with the problem and peel more layers of the onion off, you can often times arrive at some very elegant and simple solutions.';

        this.ts = new TextSwapper();
        ok(this.ts, 'The TextSwapper was created successfully');

        this.textarea = document.createElement('textarea');
        this.textarea.value = this.str;
        document.body.appendChild(this.textarea);
    },
    teardown: function() {
            document.body.removeChild(this.textarea);
    }
});

test("find()", function() {
    equal(this.ts.find('When'), false, "Check it fails gracefully when no input has been set.");
    this.textarea.focus();
    equal(this.ts.find('When'), true, "Check it finds 'When' if the textarea has focus but no input has been set.");

    this.ts.setInput(this.textarea);
    this.ts.find('When');
    equal(window.getSelection().toString(), 'When', 'The word \'When\' should be highlighted');
    equal(this.ts.found[0][0], 'When', 'The word \'When\' should be in the found array');

    this.ts.find('you');
    equal(window.getSelection().toString(), 'you', 'The word \'you\' should be highlighted');
    equal(this.ts.found[1][0], 'you', 'The word \'you\' should be in the found array');
    equal(this.ts.found.length, 4 ,'Should have found 4 you\'s');

    this.ts.find('bill');
    equal(this.ts.found.length, 0, 'Check that nothing was found for \'bill\'');

    this.ts.find('[a-z]*ee[a-z]*');
    equal(window.getSelection().toString(), 'keep', 'The word \'keep\' should be highlighted');
    equal(this.ts.found[1][0], 'peel', 'The word \'peel\' should be in the found array');
    equal(this.ts.found.length, 2 ,'Should have found 2 for [a-z]*ee[a-z]*');

});

我的问题是我会以正确的方式进行吗?我的测试中有太多断言吗?我的测试应该被分解成更小的测试吗?我一直在阅读stackoverflow上的TDD,现在我已经阅读了一些让我觉得我做错了的东西。

4

2 回答 2

5

If you are using TDD then you should go for one assertion for each test method.

The following link has a nice explanation of the problems you can run into when testing everything in one method: Unit testing It could more easily introduce hidden bugs in your code.

于 2011-10-19T14:35:21.710 回答
0

如果你能找到 Bob Martin 的“清洁代码”的副本,他会在单元测试一章中讨论这个问题。他的观点是“每个测试一个断言”可能有点尴尬(他在书中给出了一个很好的例子),他更喜欢“每个测试一个概念”。因此,如果您觉得它们密切相关并且分开会很烦人,请继续使用多个断言。

于 2015-08-15T00:35:30.150 回答