确切的论点与Minitest模拟期望相匹配?

时间:2015-01-15 00:23:57

标签: ruby mocking minitest

我正在编写Minitest单元测试,需要检查测试中的代码是否从HTTP响应模拟中提取特定的哈希值。所以我设定了以下期望:

@http_response.expect :[], 3141, [ "X-Pagination-TotalElements" ]
@http_response.expect :[], 32, [ "X-Pagination-TotalPages" ]

然而,似乎匹配基于大小写相等,第二个期望覆盖第一个。

完成我想要做的事情的正确方法是什么?

1 个答案:

答案 0 :(得分:2)

  

然而似乎匹配是基于案例相等[===]

... String类与==相同。

  

第二个期望优先于第一个。

expect statementsMiniTest::Mock个对象的排序似乎很重要:

require 'minitest/autorun'

resp = MiniTest::Mock.new
resp.expect :[], 3141, ["X-Pagination-TotalElements"]
resp.expect :[], 32, ["X-Pagination-TotalPages"]

puts resp["X-Pagination-TotalElements"]
puts resp["X-Pagination-TotalPages"]

--output:--
3141
32
Run options: --seed 29457

# Running:

Finished in 0.001500s, 0.0000 runs/s, 0.0000 assertions/s.

0 runs, 0 assertions, 0 failures, 0 errors, 0 skips

但这失败了:

require 'minitest/autorun'

resp = MiniTest::Mock.new
resp.expect :[], 3141, ["X-Pagination-TotalElements"]
resp.expect :[], 32, ["X-Pagination-TotalPages"]

puts resp["X-Pagination-TotalPages"]
puts resp["X-Pagination-TotalElements"]
  

- 输出: -
  /Users/7stud/.rvm/gems/ruby-2.1.2/gems/minitest-5.4.0/lib/minitest/mock.rb:148:in   method_missing': mocked method :[] called with unexpected arguments ["X-Pagination-TotalPages"] (MockExpectationError) from 1.rb:7:in

数量也起到了作用:

require 'minitest/autorun'

resp = MiniTest::Mock.new
resp.expect :[], 3141, ["X-Pagination-TotalElements"]

puts resp["X-Pagination-TotalElements"]
puts resp["X-Pagination-TotalElements"]
  

- 输出: -
  3141

     

/Users/7stud/.rvm/gems/ruby-2.1.2/gems/minitest-5.4.0/lib/minitest/mock.rb:122:in   method_missing': No more expects available for :[]: ["X-Pagination-TotalElements"] (MockExpectationError) from 1.rb:7:in

结果,意思是:

resp.expect :[], 3141, ["X-Pagination-TotalElements"]
resp.expect :[], 32, ["X-Pagination-TotalPages"]

..是:

  1. 我希望最初使用“X-Pagination-TotalElements”键调用resp[]将返回3141.

  2. 我希望使用“X-Pagination-TotalPages”键再次调用resp[]将返回32.

  3. 我希望任何不按此顺序的其他来电或来电都会导致失败。

  4. ...

      

    完成我想要做的事情的正确方法是什么?

    按照在代码中调用它们的顺序添加expect语句。