Javascript QUnit:每个方法一个测试,有多个断言,还是每个方法多个测试?

Javascript QUnit:每个方法一个测试,有多个断言,还是每个方法多个测试?,javascript,unit-testing,qunit,Javascript,Unit Testing,Qunit,我已经决定为我的下一个javascript项目启动TDD,并使用QUnit进行单元测试。我对单元测试完全陌生,从未用任何语言进行过。下面是我的一个模块加上find方法的一个测试的示例,该方法尝试覆盖此方法将遇到的所有场景: module("TextSwapper", { setup: function() { this.str = 'When you first start off trying to solve a problem, the first solutio

我已经决定为我的下一个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,现在我读到了一些让我觉得自己做得不对的东西。

如果您使用TDD,那么您应该为每个测试方法使用一个断言


下面的链接很好地解释了在用一种方法测试所有东西时可能遇到的问题:它可以更容易地在代码中引入隐藏的bug。

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

这是否更适合程序员。stackexchange.com?我想我不是在问代码细节,而是一个最佳实践问题。如果是的话,它能被迁移吗?我在这里没有得到太多的乐趣…可能重复的谢谢你,这个链接是有帮助的。