2013-10-07 38 views
2

我正在尝试为我的ruby脚本编写一些单元测试。然而,它不工作,因为我认为它应该工作,并且在某些测试中,它只是停在单元测试的一半。当添加某些断言时,单元测试停止一半

这是我正在测试的方法。现在

#!/usr/bin/env ruby 
require 'ptools' 
require 'test/unit' 

class InputValidators 
    # checks whether the input file exist. 
    def input_file_validator(input_file) 
     begin 
      raise ArgumentError, "Error: Input file \"#{input_file}\" does not exist. \n" unless File.exist?(input_file) 
      raise ArgumentError, "Error: Input file is empty. Please correct this and try again. \n" if File.zero?(input_file) 
      raise ArgumentError, "Error: Input file is in binary format - only text based input files are supported. \n" if File.binary?(input_file) 
     rescue Exception => e 
      puts # a empty line 
      puts e.message 
      puts # a empty line 
      Process.exit(true) 
     end 
    end 
end 

class UnitTests < Test::Unit::TestCase 
    def test_input_file_validator_1 
     test_validators = InputValidators.new 
      assert_equal(nil, test_validators.input_file_validator("./test_inputs/genetic.fna")) #file is present 
      assert_raise(SystemExit) {test_validators.input_file_validator("./test_inputs/missing_input.fna")} # file doesn't exist 
#   assert_equal(nil, test_validators.input_file_validator("./test_inputs/empty_file.fna")) # empty file 
#   assert_equal(nil, test_validators.input_file_validator("./test_inputs/binary_file.fna")) # a binary file 
    end 
end 

,如果我离开脚本如上,单元测试工作完美...

电流输出:

Run options: 

# Running tests: 

[1/1] UnitTests#test_input_file_validator_1 

Error: Input file "./test_inputs/missing_input.fna" does not exist. 

Finished tests in 0.004222s, 236.8797 tests/s, 473.7593 assertions/s. 
1 tests, 2 assertions, 0 failures, 0 errors, 0 skips 

ruby -v: ruby 2.0.0p247 (2013-06-27 revision 41674) [x86_64-linux] 

但是,如果我甚至取消对其他的一个断言,单元测试刚刚停止并且没有完成。

输出(在取消只是在上面的脚本断言的一个或两个时):

Run options: 

# Running tests: 

[1/1] UnitTests#test_input_file_validator_1 
Error: Input file "./test_inputs/missing_input.fna" does not exist. 


Error: Input file is empty. Please correct this and try again. 

我不知道我在做什么错了,所以有这方面的帮助将非常感激。 让我知道你是否需要更多信息。

回答

2

好吧,如果您运行的是exit并且您没有从该异常中拯救,那么您的进程就会停止运行。

我想assert_raise实际上捕捉错误或做一些其他的魔术来完成该过程。运行at_exit挂钩可能是一些魔术技巧。

尽管如此,对工作流程使用例外被认为是不好的做法。所以我不会建议提出一个错误,然后立即捕获它只是退出该过程。我通常只使用abort附带消息。

+0

谢谢,这是我第一次使用ArgumentErrors,所以你建议提出一个参数错误或者我应该提出参数错误,然后中止或应该只是做出条件和中止声明。 –

+0

提出错误,并在其他地方处理它,如果你想测试它。我什至不打扰,只是在我的脚本检查,因为它不会功能反正,如果该文件不存在 – phoet

相关问题