为什么在不同的单元测试中访问此实例变量时为 nil?

发布于 2024-09-10 05:48:07 字数 621 浏览 7 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

情绪 2024-09-17 05:48:07

不同之处在于您在第二个测试中没有调用 @thing.set_stuff 。

The difference looks to be that you're not calling @thing.set_stuff in the second test.

深白境迁sunset 2024-09-17 05:48:07

我不像 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文