Afficher un message
Vieux 04/11/2007, 08h31   #3
bbxx789_05ss@yahoo.com
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: How do you write a unit test of methods that needs user inpu

Feng Tien wrote:
> Will I need to change my code or is there a way for me to write my unit
> test that automatically enters some inputs?
>


It's somewhat difficult. This works for me:

my_program.rb:
--------------
def get_input
while true
print "Enter a non-zero integer greater than -5: "
num = gets

num_int = num.to_i
num_float = num.to_f

if num_int != num_float
puts "You entered a float. Try again."
elsif num_int <= -5
puts "You entered a number that was too small."
elsif num_int == 0
puts "You entered 0 or a word. That is not allowed."
else
return num_int
end

end
end

if __FILE__ == $0
result = get_input
puts "You entered #{result}. Thank you."
end



my_program_UnitTest.rb
--------------
require 'my_program'
require 'test/unit'
require 'stringio'

class TestMyProgram < Test::Unit::TestCase

def setup
$stdin = DATA #DATA is like a file containing the stuff after
__END__
trash_can = StringIO.new
$stdout = trash_can

#If you want to see the prompts shown to the user as part of
#the unit test output and/or be able to send output to your
#terminal for debugging, comment out the previous line.
end

def teardown
$stdin = STDIN
$stdout = STDOUT
end

def test_get_input
while not DATA.eof?
num = get_input

num_int = num.to_i
num_float = num.to_f

assert_not_equal(0, num_int)
assert(num_int > -5, "The number was not greater than -5.")
assert_equal(num_int, num_float)
end
end
end

__END__
-6
-4
0
2.5
6 #Must end the data with a good number--otherwise get_input will
#run out of data, causing gets in get_input to return nil, which
will
#cause get_input to go into an infinite loop.


> Idealy, I'd like to do it so that when I run my unit test, It'll ask me
> for the inputs.
>


After typing in 5 - 10 different numbers into the command line for hours
on end, you will probably think differently about testing code by hand.
In fact, if you are going to test code by hand, you don't need unit
testing. Unit testing is designed to enable you to test your program by
driving it with another program. That allows you to do tests relatively
quickly and thoroughly--and the tests are repeatable.
--
Posted via http://www.ruby-forum.com/.

  Réponse avec citation
 
Page generated in 0,06202 seconds with 9 queries