7

假设有潜在的昂贵操作要执行,setup或者teardown对于所有测试都是相同的,并且在测试运行期间其结果不会被弄乱。在我看来,让它们在每次测试之前/之后运行似乎是不对的。

那么只有在第一次测试执行之前和最后一次测试运行之后才运行设置/拆卸代码的首选方法吗?

编辑:我正在处理的特殊情况应该测试 Net::FTP 的一些扩展,从而建立一个 FTP 连接并设置一些远程对象进行测试:

class TestFTPExtensions < Test::Unit::TestCase
  def setup
    # Setup connection
    @ftp = Net::FTP.new 'localhost', 'anonymous'
    @ftp.passive = true

    # Create remote test directory
    @ftp.mkdir 'dir'

    # Create remote test file
    path = File.join Dir.tmpdir, 'file'
    File.open path, 'w' do |f|
      @ftp.put f
    end
    File.delete path
  end

  def teardown
    @ftp.rmdir 'dir'
    @ftp.delete 'file'
    @ftp.close
  end

  # imagine some tests here that don't change/remove any remote objects

end
4

1 回答 1

7

感谢 Andrew,我在 stackoverflow 上找到了答案。

然而,在试图找到答案的过程中,我还注意到在 1.9.x 分支中,标准测试框架已切换到 MiniTest。所以实际上我现在正在使用它进行测试。这个答案解释了如何使用 MiniTest 实现相同的目标。

于 2012-02-09T19:55:16.810 回答