簡體   English   中英

如何在Ruby模塊中模擬方法?

[英]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而不是返回3powering 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM