2015-09-09 53 views
0

我是BDD集成測試的忠實粉絲,也開始考慮在單元測試中使用它們。從其他問題(例如,這一個1),我可以看到人們普遍認爲編寫BDD風格的單元測試是可以接受的。但是,我還沒有看到任何使用BDD語言進行單元測試的例子。看到一些具體的例子會幫助我更好地理解它。使用BDD語言編寫單元測試的好例子?

我想知道如何使用BDD,當測試正在檢查用戶不會遇到的低級系統行爲。對於積分/視圖測試,我會做這樣的事情:

describe('Given that an author is using the question editor with a choice matrix question open ', function() { 
    describe('When the author clicks the 'Allow Multiple Responses' switch', function() { 
    it('Then the question preview should change from radio buttons to checkboxes', function() { 
     expect(....); 
    }); 
    }); 
}); 

但什麼,如果我測試低水平方法的功能?如果我試圖測試用戶永遠不會碰它的低級單元,它是否爲反模式?例如,如果我想用茉莉花來測試一個名爲isCellShadedByAuthor()方法的功能,我最好的猜測是做這樣的事情:

describe("Given that the cell is in the response area not on the author side", function() { 
    it("When the cell is an author shaded cell, then isCellShadedByAuthor should return true", function() { 
     expect(isCellShadedByAuthor(1, 3)).toBeTruthy(); 
    }); 
)); 

我想另一種方式來處理這個情況,試圖將測試提升到視圖測試,根據CSS類的存在來斷言,而不是直接聲明isCellShadedByAuthor()的返回值。這會減少測試與實現細節的耦合。

例如,我可以做

describe("Given that the cell is in the response area not on the author side", function() { 
    it("When the user hovers over an author shaded cell, then the cell should have the hover class", function() { 
     var cell = $('shading-cell[data-attribute-x="1"][data-attribute-y="1"]); 
     expect(cell.hasClass('hover-disabled')).toBeTruthy(); 
    }); 
)); 

回答

0

我不知道,如果你質疑純粹涉及到的JavaScript,但我肯定用於在以前的僱主Java項目BDD的單元測試。我們利用Mockito庫中的BDDMockito類。

我們在我們的IDE中創建了一個非常簡單的BDD單元測試模板,我們都共享它。

public void shouldDoFooOnBar() { 
    //given (perform setup here) 
    <code to define state of system>   

    //when 
    <single call to code under test> 

    //then 
    <code to assert expectations> 
} 

我們發現這給了我們的測試一個很好的一致結構,很容易閱讀。

這裏是一個的Mockito具體的例子:

public void shouldBuyBread() throws Exception { 
    //given 
    given(seller.askForBread()).willReturn(new Bread()); 

    //when 
    Goods goods = shop.buyBread(); 

    //then 
    assertThat(goods, containBread()); 
} 

值得一提的是,我們還使用BDD在集成測試級別,但對於這個我們使用FitNesse

相關問題