![](/img/trans.png)
[英]How to mock an actual Object#method call using Mocha in Ruby?
[英]How to mock a method call in Ruby
我正在為A類編寫一種稱為m()的測試方法。
m()通過稱為“ b”的B實例在類B上調用f(),但我使用以下方法模擬了該方法調用:
def test_m
@a = A.new
b_mock = MiniTest::Mock.new
b_mock.expect(:f, 'expected_output')
def b_mock.f()
return 'expected output'
end
@a.b = b_mock
end
現在,A具有另一個方法m1(),如何使用Minitest的上述方法或更好的方法來模擬對它的調用並獲得恆定的輸出?
錯誤-
NoMethodError: unmocked method :get_group_by_name, expected one of [:]
您可以使用MiniTest Object#stub方法,它在塊持續時間內重新定義方法結果。
require 'minitest/mock'
class A
def m1
m2
'the original result'
end
def m2
'm2 result'
end
end
@a = A.new
@a.stub :m1, "the stubbed result" do
puts @a.m1 # will print 'the stubbed result'
puts @a.m2
end
了解更多: http : //www.rubydoc.info/gems/minitest/4.2.0/Object : stub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.