2015-09-09 52 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

相关问题