[英]Ruby MiniTest UnitTest Stubbing Class method just for one test
I want to stub a class method for just one test and for the rest of the tests, i want the actual method to be called. 我想为一个测试存在一个类方法,对于其余的测试,我希望调用实际的方法。 I have always been using rspec and mocha, so the below behavior looks bizarre.
我一直在使用rspec和mocha,所以下面的行为看起来很奇怪。
The class that i want to stub in one of my tests. 我希望在我的一个测试中存根的类。
class MyClass
def self.foo(arg)
return "foo#{arg}"
end
end
The test where i try to stub MyClass.foo 测试我尝试存根MyClass.foo
class XYZTest < Minitest::Test
def test_1
MyClass.expects(:foo).returns('abcd')
assert_equal MyClass.foo('123'), 'abcd'
end
def test_2
assert_equal MyClass.foo('123'), 'foo123'
end
end
The first test passes, but the second test fails stating Mocha::ExpectationError: unexpected invocation: MyClass.foo('123') 第一个测试通过,但第二个测试失败,说明Mocha :: ExpectationError:意外调用:MyClass.foo('123')
In the test_2, i want the actual class method to be called instead of the stub that i did in test_1. 在test_2中,我希望调用实际的类方法而不是我在test_1中执行的存根。
PS: Above is a striped down example. PS:上面是一个条纹下来的例子。 I do not want to reset everytime, I stub the class method.
我不想每次都重置,我存在类方法。
Minitest stubs methods within a block, so what you're trying to do is simple. 块中的Minitest存根方法,所以你要做的就是简单。
class XYZTest < Minitest::Test
# stubbed here
def test_1
MyClass.stub(:foo, 'abcd') do
assert_equal MyClass.foo('123'), 'abcd'
end
end
# not stubbed here
def test_2
assert_equal MyClass.foo('123'), 'foo123'
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.