代码之家  ›  专栏  ›  技术社区  ›  Andy_Vulhop

在一个给定的when-then语句中列出集合的所有部分,还是分解为单独的规范?

  •  0
  • Andy_Vulhop  · 技术社区  · 14 年前

    在编写给定的when-then-specs语句时,您更喜欢在1 when语句中列出集合中的元素,还是为每个元素分别执行一个规范?

    GIVEN a book 
    WHEN category is "Fanatsy", "Sci-Fi", or "Horror" 
    THEN Buy it. 
    

    VS

    GIVEN a book
    WHEN category is "Fanatsy"
    THEN Buy it.
    
    GIVEN a book 
    WHEN category is "Sci-Fi"
    THEN Buy it.
    
    GIVEN a book 
    WHEN category is "Horror" 
    THEN Buy it.
    

    另外,你对剩下的部分做了什么?您是否为不在“一目了然”子集中的每个类别编写规范,以确保它不会购买?

    1 回复  |  直到 14 年前
        1
  •  1
  •   Michael Meadows    14 年前

    最好能将它们分开,因为这样更容易确定哪一个失败了。例如,如果你的测试没能买到“科幻小说”,但在“幻想”和“恐怖”上取得成功,你怎么知道哪一部失败了?最困难的部分是诱使你的语言允许你这样做而不重复你自己一次又一次。

    这在一维问题上并不像在多维问题上那样有问题,例如:

    GIVEN a bookstore
    THAT has "Fantasy", "Sci-Fi", and "Horror" books
    WHEN you only have enough money to buy one book
    THEN buy "Fantasy"
    

    GIVEN a bookstore
    THAT has "Fantasy", "Sci-Fi", and "Horror" books
    WHEN you have enough money to buy two books
    THEN buy "Fantasy" and "Sci-Fi"
    

    GIVEN a bookstore
    THAT has "Fantasy", "Sci-Fi", and "Horror" books
    WHEN you have enough money to buy two books
    AND you already own a "Fantasy" book
    THEN buy "Sci-Fi" and "Horror"
    

    在这些情况下,我的投票结果仍然是你将其分解为:

    GIVEN a bookstore
    THAT has "Fantasy", "Sci-Fi", and "Horror" books
    WHEN you have enough money to buy two books
    AND you already own a "Fantasy" book
    THEN buy "Sci-Fi"
    THEN buy "Horror"
    

    这意味着在上面的例子中有两个规格。不过,在静态语言中,比如C语言和Java,我还没有找到一个很好的方法来实现这一点。有一点很有帮助,那就是将您的排列和断言代码分解为可重用的方法,并像从自助餐厅中挑选菜肴一样从中挑选:

    public virtual void Establish_context()
    {
        Given_a_bookstore_that_has_Fantasy_Sci_fi_and_Horror_books();
        When_you_have_enough_money_to_buy_two_books();
        And_you_already_own_a_fantasy_book();
    }
    
    [Specification]
    public void Then_buy_Sci_fi()
    {
    }
    
    [Specification]
    public void Then_buy_Horror()
    {
    }
    

    现在,您可以创建多个子类,混合并匹配您的给定和时间。它减少了痛苦,但仍然突出了静态类型语言在编写真正流畅的BDD风格代码方面的缺点。