我在class QuestionList
def ask_all
@questions.each do |question|
question.ask
@player.add_answer(gets.chomp)
end
end
问题有整数答案,并且答案不必对于此测试是正确的 - 只需要在{{1 }}
@player.answers
如何在单元测试方法时模拟class Player
def add_answer(answer)
@answers << answer
end
的用户输入:
gets.chomp
答案 0 :(得分:1)
ask_all
修改为输入不可知:def ask_all
@questions.each do |question|
question.ask
@player.add_answer(question.retrieve_answer)
end
end
Question
类以使用retrieve_answer
方法:class Question
def ask
# even better, delegate this to some other class
# to make it possible to work with console,
# batches, whatever depending on settings
print "Enter an answer >"
end
def retrieve_answer
# for now it’s enough
gets.chomp
end
end
Question
课程以交互方式“提问”:class QuestionListTest < Test::Unit::TestCase
def setup
Question.define_method :ask do
print "I am mock for prompting ... "
end
Question.define_method :retrieve_answer do
# be aware of wrong input as well!
[*(1..10), 'wrong input', ''].sample.tap do |answer|
puts "mocked answer is #{answer}."
end
end
end
def test_ask_all
expect(ask_all).to match_array(...)
end
end