[英]How to mock a method in a module in ruby?
我有與內容的number_module.rb
:
def power2(x)
x * x
end
和測試用例tc_number.rb
:
require_relative('number_module')
require "test/unit"
require 'mocha/test_unit'
class TestSimpleNumber < Test::Unit::TestCase
def test_simple
assert_equal(4, power2(2) ) # how to mock power2 to return 3?
end
end
為了練習模擬,我想在測試用例中模擬power2以返回3
而不是返回3
的powering by 2
我該怎么做?
從文檔中看來,您可以只使用expects(:method_name).returns(result)
:
def power2(x)
x * x
end
require "test/unit"
require 'mocha/test_unit'
class TestSimpleNumber < Test::Unit::TestCase
def test_simple
expects(:power2).returns(3)
assert_equal(4, power2(2) )
end
end
測試失敗,如預期的那樣:
Loaded suite mocha
Started
F
=============================================================================================================================================================
Failure: test_simple(TestSimpleNumber)
mocha.rb:10:in `test_simple'
7: class TestSimpleNumber < Test::Unit::TestCase
8: def test_simple
9: expects(:power2).returns(3)
=> 10: assert_equal(4, power2(2) ) # how to mock power2 to return 3?
11: end
12: end
<4> expected but was
<3>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.