QUnit:每个方法一个测试,多个断言或每个方法多个测试?

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相关内容,现在我已经读了一些东西,让我觉得我做错了。


这个问题更适合 programmers.stackexchange.com 吗?我想我不是在问代码细节,而是一个最佳实践的问题。如果是的话,它能被迁移吗?我在这里得不到太多帮助... - punkrockbuddyholly
可能是如何组织单元测试?的重复问题。 - Dave Schweisguth
2个回答

5
如果您正在使用TDD,那么每个测试方法应该只有一个断言。
下面的链接详细解释了在一个方法中测试所有内容可能会遇到的问题:单元测试。这种做法更容易引入隐藏的bug到您的代码中。

谢谢,那个链接很有帮助。 - punkrockbuddyholly

0
如果你能找到Bob Martin的《Clean Code》一书的副本,他在单元测试章节中讨论了这个问题。他的观点是,“每个测试一个断言”可能有点尴尬(他在书中给出了一个很好的例子),他更喜欢追求“每个测试一个概念”的目标。因此,如果你觉得多个断言密切相关且分开会很麻烦,请放心使用多个断言。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接