[英]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.