javascript
  • unit-testing
  • qunit
  • 2011-10-19 96 views 2 likes 
    2

    我已經決定爲我的下一個javascript項目開始TDD,我正在使用QUnit進行單元測試。我對單元測試完全陌生,從來沒有用過任何語言。下面是試圖覆蓋所有場景我模塊一加爲find方法一個測試的例子這個方法會遇到:QUnit:每個方法有多個斷言或每個方法多個測試的一個測試?

    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

    這是否更適合程序員.stackexchange.com?我想我不是在問關於代碼細節的問題,它更像是一個最佳實踐問題。如果這樣可以遷移?我在這裏沒有得到太多的快樂... – MrMisterMan

    +0

    可能重複[你如何組織單元測試?](http://stackoverflow.com/questions/110430/how-do-you-organize-unit-tests) –

    回答

    4

    如果您使用的是TDD,那麼您應該爲每個測試方法選擇一個斷言。

    以下鏈接對以一種方法測試所有內容時遇到的問題有很好的解釋:Unit testing它可以更容易地在您的代碼中引入隱藏的錯誤。

    +0

    謝謝,那個鏈接很有幫助。 – MrMisterMan

    0

    如果你能找到Bob Martin的「Clean Code」的副本,他在單元測試章節討論這個問題。他的觀點是,「每個測試的一個斷言」可能有點尷尬(他在本書中給出了一個很好的例子),而他更喜歡拍攝「每個測試一個概念」。因此,如果您覺得它們密切相關,並且很難分離,請繼續使用多個斷言。

    相關問題