【问题标题】:How to create test objects in tests?如何在测试中创建测试对象?
【发布时间】:2011-03-01 15:39:02
【问题描述】:

我正在为付款流程创建单元测试。大约有 20 个单元单元测试要编写 - 一些正面案例和一些负面案例。

示例:

payment_screen=PaymentScreen()

我几乎没有什么概念。

首先 - 创建一个带有属性的 Payer 对象:

payer=Payer(last_name,country_code)

country_code 很重要,因为系统不允许将物品发送到其他国家

第二

payer=Payer.return_correct_payer()

类似:

类付款人:

 @staticmethod
 def return_correct_payer():
 payer=Payer()
 payer.country_code='US'
 payer.last_name='Smith'

在两个选项中

payment_screen.fill_payer_data(payer)

还有一个概念:

在 payment_screen 中只需创建两个方法:

fill_payer_data_with_correct_data()

fill_payer_data_with_uncorrect_data()

哪个是最好的?或者也许你有别的想法(我相信你有)

编辑

感谢您的回复,但这不是我需要的。 我只是不想在每个带有属性的测试用例中创建对象 Pax。

我有 20 个测试用例,所以现在我必须写 20 次:

payer=Payer('Smith','US')

我不想重复我的代码

【问题讨论】:

    标签: python unit-testing class-design


    【解决方案1】:

    也许您正在寻找某种模拟框架。然后当你测试PaymentScreen时,你可以模拟出Payer。有关 python 模拟框架的更多信息,请查看此处:What is your favorite Python mocking library?

    【讨论】:

      【解决方案2】:

      嘿。
      可能首先用模拟回答是你需要的,但我想展示我如何在测试中创建对象。 因此,如果我需要一个具有给定参数的对象,我会使用 BuilderPattern(实际上是 GOF 修改的 BuilderPattern),如下所示:

      class User  {
          private string firstName;
          private string lastName;
      
          public User(){};
      
          //now the essence
          public User withFirstName(strFirstName) {
              this.firstName = strFirstName;
              return this;
          }
      
          public User withLastName(strLastName) {
              this.lastName = strLastName;
              return this;
          }
      
      
          //some other stuff
      }  
      

      然后我启动对象:

      User testUser1 = new User()
                                 .withFirstName("John")
                                 .withLastName("Doe");
      

      然后我用它做我需要的。

      附注对不起,代码不是 python 语法......但你应该得到它

      【讨论】:

        猜你喜欢
        • 2014-01-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-12-11
        • 1970-01-01
        • 2016-05-15
        相关资源
        最近更新 更多