1

我刚刚开始使用 GWT 方法来练习 BDD,然后才意识到我无法进行第二次测试。

我的 GWT 类似于

Given there exists an open query
When the user replies to the query
Then it should save the reply if the reply is not blank

然后它应该通知用户并且如果它是空白的则不保存回复

所以我把它编码成这样

public class when_user_replies_to_the_query : OpenQuery
{
    Because
    {
         query.Reply(data);
    }

    ThenIt should_save_the_reply_to_the_database_if_there_is_a_reply

    ThenIt should_notify_the_user_if_there_is_no_text_in_the_reply_and_not_save_to_database
}

public class Query
{
    void Reply(string data)
    {
        //do something
    }
}

但后来我意识到我不能做第二种情况,因为第一种情况要求数据中有一些东西,而第二种情况说数据应该是一个空字符串。

这是否意味着我应该将我的 GWT 拆分为类似

Given the reply is blank
When the user replies to the query
Then it should notify the user ......

如果是这种情况,那么我将编写大量的空案例场景以供返回

values being null. Such as
Given the database is null
When retrieving queries
Should reply with error message
When saving queries
Should save to file and reply with error message
When // basically doing anything
Should //give appropriate response

这是我应该如何编写 BDD 规范的方式吗?我什至在正确的论坛 O_O 中吗?

4

1 回答 1

2

您可能希望颠倒这两个Then子句,因为它们基本上形成了Query练习课程的不同上下文。当您阅读这两个Then语句时,您可以看到“if is not blank”和“is blank”形成了两个上下文。

  1. 上下文#1:

    Given an open query
    Given a non-blank reply
    When the user replies to the query
    It should save the reply
    
    public class When_the_user_replies_to_the_query_and_the_reply_is_not_blank
    {
       static Query Query;
    
       Establish context = () =>
       {
           Query = new Query();
       };
    
       Because of = () =>
       {
           Query.Reply("answer");
       };
    
       It should_save_the_reply = () =>
       {
           // Use your imagination
       };
    }
    
  2. 上下文#2:

    Given an open query
    Given a blank reply
    When the user replies to the query
    It should not save the reply
    It should notify the user
    
    public class When_the_user_replies_to_the_query_and_the_reply_is_blank
    {
       static Query Query;
    
       Establish context = () =>
       {
           Query = new Query();
       };
    
       Because of = () =>
       {
           Query.Reply(String.Empty);
       };
    
       It should_not_save_the_reply = () =>
       {
           // Use your imagination
       };
    
       It should_notify_the_user = () =>
       {
           // Use your imagination
       };
    }
    

考虑到您可能有多个可能的“空回复”值 ( null, String.Empty, " ", \r\n) ,您可以为其中任何一个编写上下文。我通常不会为任何可以想象的值组合编写规范,而是

  • 有一个“快乐路径”的上下文,即回复不为空
  • 有一个空回复的上下文

根据您的示例,有人可能会争辩说Query该类不是决定回复是否满足“非空”规范的正确位置。您应该将该决定编码在一个单独的类中,并且Query应该依赖于该类的决定。这会带来一些好处:

  • 关注点分离:Query类和规范可以分开发展
  • 您可以在多个地方重复使用规范,在用户发布空回复之前提示回复存在问题
  • 您可以单独获取正在测试的规范,而无需担心用户通知和数据库保存,从而防止因Query关注点引起的上下文爆炸
于 2010-01-22T13:32:30.330 回答