用 Minitest 测试 class 的方法
Stubbing a method of tested class with Minitest
我正在编写更大框架的一部分,但遇到存根问题。这是我的
class A
def bar
# some code
foo
# some code
end
def foo
# method dependent on other parts of the framework
end
end
现在我想测试方法bar,但它依赖于foo和foo调用框架的其他部分(这更多是集成测试的问题)。我想做的是在我的测试中存根 foo,比如:
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
但是我不知道怎么做。
我想如果我理解正确的话你正在寻找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
更新:基于评论如何return多个值
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
我正在编写更大框架的一部分,但遇到存根问题。这是我的
class A
def bar
# some code
foo
# some code
end
def foo
# method dependent on other parts of the framework
end
end
现在我想测试方法bar,但它依赖于foo和foo调用框架的其他部分(这更多是集成测试的问题)。我想做的是在我的测试中存根 foo,比如:
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
但是我不知道怎么做。
我想如果我理解正确的话你正在寻找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
更新:基于评论如何return多个值
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