Ruby:使用Flexmock进行模拟文件写入

时间:2012-07-13 16:13:52

标签: ruby unit-testing mocking

如果之前有人问过道歉。

一个简单的课程:

class AskSO

  def initialize( filehandle )
    @filehandle   = filehandle
  end

  def library_start
    @filehandle << '<plist version="1.0">'
  end
end

使用Flex mock进行简单的单元测试

require 'rubygems'
require 'flexmock/test_unit'
require 'AskSO'
require 'test/unit'

class AskSOTest < Test::Unit::TestCase

  def setup
    @filehandle = flexmock( "filehandle", "<<" => "" )
  end

  def test_library_start
    @filehandle.should_receive( "<<" ).with( '<plist version="1.0">' ).once
    @AskSOInstance = AskSO.new( @filehandle )
    @AskSOInstance.library_start
  end
end

当我使用ruby AskSO-test.rb运行时,我得到了

  1) Failure:
test_library_start(AskSOTest)
    [/Library/Ruby/Gems/1.8/gems/flexmock-0.9.0/lib/flexmock/validators.rb:40:in `validate'
     /Library/Ruby/Gems/1.8/gems/flexmock-0.9.0/lib/flexmock/expectation.rb:123:in `flexmock_verify'
     /Library/Ruby/Gems/1.8/gems/flexmock-0.9.0/lib/flexmock/expectation.rb:122:in `each'
     /Library/Ruby/Gems/1.8/gems/flexmock-0.9.0/lib/flexmock/expectation.rb:122:in `flexmock_verify'
     /Library/Ruby/Gems/1.8/gems/flexmock-0.9.0/lib/flexmock/expectation_director.rb:64:in `flexmock_verify'
     /Library/Ruby/Gems/1.8/gems/flexmock-0.9.0/lib/flexmock/expectation_director.rb:63:in `each'
     /Library/Ruby/Gems/1.8/gems/flexmock-0.9.0/lib/flexmock/expectation_director.rb:63:in `flexmock_verify'
     /Library/Ruby/Gems/1.8/gems/flexmock-0.9.0/lib/flexmock/core.rb:76:in `flexmock_verify'
     /Library/Ruby/Gems/1.8/gems/flexmock-0.9.0/lib/flexmock/core.rb:75:in `each'
     /Library/Ruby/Gems/1.8/gems/flexmock-0.9.0/lib/flexmock/core.rb:75:in `flexmock_verify'
     /Library/Ruby/Gems/1.8/gems/flexmock-0.9.0/lib/flexmock/core.rb:191:in `flexmock_wrap'
     /Library/Ruby/Gems/1.8/gems/flexmock-0.9.0/lib/flexmock/core.rb:74:in `flexmock_verify'
     /Library/Ruby/Gems/1.8/gems/flexmock-0.9.0/lib/flexmock/mock_container.rb:40:in `flexmock_verify'
     /Library/Ruby/Gems/1.8/gems/flexmock-0.9.0/lib/flexmock/mock_container.rb:39:in `each'
     /Library/Ruby/Gems/1.8/gems/flexmock-0.9.0/lib/flexmock/mock_container.rb:39:in `flexmock_verify'
     /Library/Ruby/Gems/1.8/gems/flexmock-0.9.0/lib/flexmock/mock_container.rb:32:in `flexmock_teardown'
     /Library/Ruby/Gems/1.8/gems/flexmock-0.9.0/lib/flexmock/test_unit.rb:26:in `teardown']:
in mock 'filehandle': method '<<("<plist version=\"1.0\">")' called incorrect number of times.
<1> expected but was
<0>.

我做错了什么?提前谢谢

1 个答案:

答案 0 :(得分:0)

回答我自己的问题以防其他人偶然发现同一问题 - 将模拟定义更改为

def setup
  @filehandle = flexmock( "filehandle" )
end

即没有方法。出于同样的原因,这解决了问题