Mocking an external API

亡梦爱人 提交于 2021-01-24 07:08:37

问题


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.

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.

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 => {
      ...
      }
    }
  )

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

I figure I have to do something like:

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.


回答1:


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))

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



来源:https://stackoverflow.com/questions/3401199/mocking-an-external-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!