【问题标题】:Good example of using BDD language to write unit tests?使用 BDD 语言编写单元测试的好例子?
【发布时间】:2015-09-09 05:21:39
【问题描述】:

我非常喜欢使用 BDD 进行集成测试,并且已经开始考虑在单元测试中使用它们。从其他问题(例如这个1)中,我可以看到人们普遍认为编写 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(....);
     });
  });
});

但是如果我正在测试低级方法的功能呢?如果我试图测试用户永远不会触摸的低级单元,这是否是一种反模式?例如,如果我想使用 Jasmine 来测试一个名为 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();
  });
));

【问题讨论】:

    标签: unit-testing jasmine bdd


    【解决方案1】:

    我不确定您的问题是否纯粹与 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-04
      • 1970-01-01
      • 1970-01-01
      • 2011-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多