用Minitest伪造一个测试类的方法

时间:2017-03-22 13:17:29

标签: ruby minitest

我正在编写更大框架的一部分,我遇到了存根问题。这就是我所拥有的

class A
    def bar
        # some code
        foo
        # some code
    end
    def foo
        # method dependent on other parts of the framework
    end
end

现在我想测试方法栏,但它依赖于foo和foo调用框架的其他部分(这更像是集成测试的问题)。我想做的是在测试中使用stub,例如:

class TestA < Minitest::Test
    def stubbed_foo
        return 5
    end
    def test_bar
        a = A.new
        # use stubbed_foo in a instead of foo
        result = a.bar 
        # some assert
    end
end

但我不知道该怎么做。

1 个答案:

答案 0 :(得分:1)

我想如果我理解正确你正在寻找MiniTest::Object#stub

def test_bar
    a = A.new
    # use stubbed_foo in a instead of foo
    a.stub :foo, 5 do 
      result = a.bar 
      # some assert
    end
end

以下是一个完整的例子:

require 'minitest/autorun'

class A 
    def bar
        foo + 1
    end
    def foo 
        3
    end
end

class TestA < MiniTest::Unit::TestCase

    def test_bar
        a = A.new
        a.stub :foo, 5 do 
            result = a.bar
            assert_equal(6,result)
        end
    end

  def test_actual_bar
    a = A.new
    result = a.bar
    assert_equal(4,result)
  end
end

更新:根据评论如何返回多个值

class A 
  def bar
    foo + 1
  end
  def foo 
    3
  end
end

class TestA < MiniTest::Unit::TestCase

  def test_bar
    a = A.new
    stubbed_foo = [5,7].to_enum
    a.stub :foo, ->{stubbed_foo.next} do  
      assert_equal(6,a.bar)
      assert_equal(8,a.bar)
    end
  end

  def test_actual_bar
    a = A.new
    assert_equal(4,a.bar)
  end
end