2011-10-19 4 views
2

私は次のjavascriptプロジェクトのためにTDDに着手することに決めました。私は単体テストのためにQUnitを使っています。私は単体テストにはまったく新しいです。ここに私のモジュールの一つに加えて、この方法が遭遇するすべてのシナリオをカバーしようとするfind方法のための1つのテストの例です:QUnit:方法ごとに複数のアサーションまたは複数のテストを使用する方法ごとに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を読んできましたが、私はこれを間違ってやっているように感じています。

+0

これはプログラマに適していますか?私はコードの詳細について質問していないと思いますが、それはベストプラクティスの質問のほうです。もしそうなら、それは移行することができますか?私はここで多くの喜びを得ていません... – MrMisterMan

+0

[どのようにあなたは単体テストを構成しますか?](http://stackoverflow.com/questions/110430/how-do-you-organize-unit-tests) –

答えて

4

TDDを使用している場合、テスト方法ごとに1つのアサーションを行う必要があります。

次のリンクは、すべてのメソッドを1つのメソッドでテストするときに実行できる問題について素敵な説明をしています。Unit testingコードに隠れたバグが入りやすくなります。

+0

ありがとう、そのリンクが役立ちます。 – MrMisterMan

0

ボブ・マーティンの「クリーン・コード」のコピーがある場合は、ユニット・テストの章でこの問題について説明します。彼の意見は、「テストごとに1つのアサーション」が少し不自然になりうることです(彼は本の中の良い例を示しています)。代わりに、「テストごとに1つのコンセプト」を撮影する方が好きです。そうすれば、複数のアサーションが密接に関連していると感じる場合は、複数のアサーションを使用して、分離するのは面倒です。

関連する問題