模拟外部 API [英] Mocking an external API

查看:38
本文介绍了模拟外部 API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new to testing strategies and mocking, and I'm having a tough time figuring out how to mock a call to an external service. I'm sure it's something easy I'm missing, I just don't know what exactly.

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

I'm using the Braintree gem to charge for subscription services through the Braintree gateway, and I wanted to mock the Customer create method and Subscription create method in my UserController's create method.

Customer.create 方法如下所示:

A Customer.create method looks something like this:

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

这将返回一个 Braintree::Successful 结果对象,带有处理结果的属性.

This returns a Braintree::Successful result object, with the attributes of the processed result.

我想我必须这样做:

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

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

But what goes in the returns area? Do I need to create my own mocked up Successful object with the attributes of a faked processed result, or is there an easier way to do all of that?

感谢您提供的任何帮助.

Thanks for any help you can provide.

推荐答案

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

You can return an OpenStruct as suggested in the comment or a stub or mock, which is IMHO better and more useful for tests, because you can easily set expectations, like this:

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

返回的模拟将期望 save 消息(在这种情况下可能没有意义,但应该给你一个想法).

The returned mock will expect the save message (which may not make sense in this case, but should give you the idea).

这篇关于模拟外部 API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆