【问题标题】:Mocking an external API模拟外部 API
【发布时间】:2010-08-03 22:17:49
【问题描述】:

我是测试策略和模拟的新手,我很难弄清楚如何模拟对外部服务的调用。我确定这很容易我错过了,我只是不知道到底是什么。

我正在使用 Braintree gem 通过 Braintree 网关对订阅服务收费,我想在我的 UserController 的 create 方法中模拟 Customer create 方法和 Subscription create 方法。

Customer.create 方法如下所示:

  result = Braintree::Customer.create(
    :first_name => @creditcard.first_name,
    :last_name => @creditcard.last_name,
    :email => @user.email
    :credit_card => {
      ...
      }
    }
  )

这将返回一个 Braintree::Successful 结果对象,以及处理结果的属性。

我想我必须这样做:

Braintree::Customer.expects(:create).returns(...)

但是退货区有什么?我是否需要使用伪造的处理结果的属性创建自己的模拟成功对象,还是有更简单的方法来完成所有这些?

感谢您提供的任何帮助。

【问题讨论】:

  • 你需要返回一些对象,要么是或“像” Braintree::Customer 我有时只使用 OpenStruct
  • 啊,我想这正是我正在寻找的东西。只是模仿相同基本结构的东西。谢谢!

标签: ruby-on-rails ruby unit-testing testunit ruby-mocha


【解决方案1】:

您可以按照评论中的建议返回OpenStruct,或者返回stub 或mock,恕我直言,这对测试更好、更有用,因为您可以轻松设置期望值,如下所示:

Braintree::Customer.expects(:create).returns(mock(:save => true))

返回的 mock 将期待 save 消息(在这种情况下可能没有意义,但应该会给你这个想法)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-08-11
    • 1970-01-01
    • 2015-03-20
    • 1970-01-01
    • 1970-01-01
    • 2022-10-24
    • 2016-04-15
    • 2021-10-31
    相关资源
    最近更新 更多