为什么在不同的单元测试中访问此实例变量时为 nil?
require 'rubygems'
require 'test/unit'
class Thing
attr_accessor :foo
def set_stuff
@foo = 'bar'
end
end
class ThingTest < Test::Unit::TestCase
def setup
@thing = Thing.new
end
def test_set_stuff
@thing.set_stuff
assert 'bar' == @thing.foo
end
def test_foo_in_other_test
puts @thing.foo
assert 'bar' == @thing.foo
end
end
# Loaded suite testing
# Started
# nil
# F.
# Finished in 0.00439 seconds.
#
# 1) Failure:
# test_foo_in_other_test(ThingTest) [testing.rb:26]:
# <false> is not true.
#
# 2 tests, 2 assertions, 1 failures, 0 errors
require 'rubygems'
require 'test/unit'
class Thing
attr_accessor :foo
def set_stuff
@foo = 'bar'
end
end
class ThingTest < Test::Unit::TestCase
def setup
@thing = Thing.new
end
def test_set_stuff
@thing.set_stuff
assert 'bar' == @thing.foo
end
def test_foo_in_other_test
puts @thing.foo
assert 'bar' == @thing.foo
end
end
# Loaded suite testing
# Started
# nil
# F.
# Finished in 0.00439 seconds.
#
# 1) Failure:
# test_foo_in_other_test(ThingTest) [testing.rb:26]:
# <false> is not true.
#
# 2 tests, 2 assertions, 1 failures, 0 errors
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不同之处在于您在第二个测试中没有调用 @thing.set_stuff 。
The difference looks to be that you're not calling @thing.set_stuff in the second test.
我不像 RSpec 那样熟悉 Test::Unit,但我相信每次运行测试时都会调用 setup() 方法。所以一个@thing会被另一个@thing覆盖。
此外,我发现您不能假设测试用例的执行特定顺序;通常(也许一直?)测试是从最后到第一个运行的,就像本例中的情况一样。
I'm not as familiar with Test::Unit as RSpec, but I believe the setup() method will be called each time a test is run. So one @thing will be overwritten by another.
In addition, I've found that you can't assume a particular order for the execution of test cases; often (perhaps all the time?) the tests are run from last to first, as seems to be the case in this instance.