[Ruby] HTTP mock 库 webmock

最近又在做RESTful的应用开发,自动化测试使用的Ruby写脚本。

运用BDD/TDD的开发思路,希望能先从使用Mock表达行为开始

这里使用如Ruby的webmock框架 (gem install webmock)来尝试

require "test/unit"
require "shoulda"

require "webmock"
include WebMock::API
include Test::Unit::Assertions

class RESTfulTest < Test::Unit::TestCase
  context "Restful test case" do
    should "be equal" do
      stub_request(:any, "www.example.com").to_return(:body => {
          "a" => 1,
          "b" => 2
      })

      o = Net::HTTP.get("www.example.com", "/") # ===> Success

assert_equal(o['a'], 1) end end end

上面用到了一个stub_request的函数mock/stub了一个HTTP 请求。Unit Test的框架是test/unit + shoula

原文地址:https://www.cnblogs.com/buhaiqing/p/3064215.html