如何在Ruby中使用Mocha测试工厂模式? [英] How to test factory pattern using Mocha in Ruby?

查看:73
本文介绍了如何在Ruby中使用Mocha测试工厂模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法通过这个简单的 mocha 测试正常工作

I'm having trouble getting this simple mocha test to work

免责声明:我是摩卡新手!

我的Factory

# lib/fabtory.rb
class Factory
  def self.build klass, *args
    klass.new *args
  end
end

我的测试代码

# test/test_factory.rb
class FactoryTest < MiniTest::Unit::TestCase

  # my fake class
  class Fake
    def initialize *args
    end
  end

  def test_build_passes_arguments_to_constructor
    obj = Factory.build Fake, 1, 2, 3
    obj.expects(:initialize).with(1, 2, 3).once
  end

end

输出

unsatisfied expectations:
- expected exactly once, not yet invoked: #<Fake:0x7f98d5534740>.initialize(1, 2, 3)

推荐答案

expects方法在调用之后寻找方法调用.

The expects method look for method calls after his call.

您必须设置一些不同的地方:

You have to setup things a little bit different:

def test_build_passes_arguments_to_constructor
  fake = mock()
  Fake.expects(:new).with(1, 2, 3).returns(fake)
  assert_equal fake, Factory.build(Fake, 1, 2, 3)
end

这篇关于如何在Ruby中使用Mocha测试工厂模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆