views:

93

answers:

1

I have the following code with the corresponding test case:

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

Running the test case will produce the following result on assert_raise due to the presence of the 'rescue' routine:

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

How do I write a test case for this scenario when I cannot do away with removing the 'rescue' from my code?

Commenting 'rescue' out produces a favorable result for me.

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
+2  A: 

Test for the actual behaviour of the method. It doesn't throw an exception it prints, so that's what you need to check for. You probably need a mock object?

djna
I think testing the actual behaviour of the method should be it. I was actually trying to test every possible wrong input passed to the method and see if it can handle it. Sorry, newbie in ruby and just dipping my hand on tdd. :)
arzon
Testing all the wrong input is surely correct. It's just how you check for correct behaviour for that wrong input.
djna