处理异常时的测试用例问题

时间:2009-08-11 05:56:31

标签: ruby unit-testing exception-handling

我有以下代码和相应的测试用例:

class XXX
    attr_accessor :source
    def check
        begin
            raise ArgumentError, "No source specified." \
                unless @source.empty? != true
            puts "Passed"
        rescue
            print "Error: ",$!, "\n"
        end
    end
end

class TestXXX < Test::Unit::TestCase
    def setup
        @x = XXX.new
    end

    def test_check
        assert_nil(@x.source)
        assert_raise(NoMethodError) { @x.check }
    end
end

由于存在'rescue'例程,运行测试用例将在assert_raise上产生以下结果:

Started
.Error: undefined method `empty?' for nil:NilClass
F
Finished in 0.01 seconds.

  1) Failure:
test_check:18 exception expected but none was thrown.

1 tests, 2 assertions, 1 failures, 0 errors

当我无法从代码中删除'rescue'时,如何为此方案编写测试用例?

评论'救援'对我来说是一个有利的结果。

class XXX
    attr_accessor :source
    def check
        begin
            raise ArgumentError, "No source specified." \
                unless @source.empty? != true
            puts "Passed"
        #rescue
        #    print "Error: ",$!, "\n"
        end
    end
end
Started
..
Finished in 0.0 seconds.

1 tests, 2 assertions, 0 failures, 0 errors

1 个答案:

答案 0 :(得分:2)

测试方法的实际行为。它不会抛出打印的异常,因此您需要检查它。您可能需要一个mock对象?