3

次のjavascriptプロジェクトでTDDに着手することにし、ユニットテストにQUnitを使用しています。私はユニットテストにまったく慣れておらず、どの言語でも行ったことがありません。これは、私のモジュールの1つと、findこのメソッドが遭遇するすべてのシナリオをカバーしようとするメソッドの1つのテストの例です。

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

TDDを使用している場合は、テストメソッドごとに1つのアサーションを実行する必要があります。

次のリンクには、1つのメソッドですべてをテストするときに発生する可能性のある問題の説明があります。単体テストコードに隠れたバグをより簡単に導入できる可能性があります。

于 2011-10-19T14:35:21.710 に答える
0

ボブ・マーチンの「クリーンコード」のコピーを見つけることができれば、彼はユニットテストの章でこの質問について議論しています。彼の意見は、「テストごとに1つのアサーション」は少し厄介な場合があり(彼は本の中で良い例を示しています)、代わりに「テストごとに1つの概念」を狙うことを好みます。したがって、それらが密接に関連していて、分離するのが面倒だと思われる場合は、先に進んで複数のアサーションを使用してください。

于 2015-08-15T00:35:30.150 に答える