[英]How can I unit test a method that takes stdin within a loop?
I have the following method in class QuestionList
我在class QuestionList
有以下方法
def ask_all
@questions.each do |question|
question.ask
@player.add_answer(gets.chomp)
end
end
The questions have integer answers, and the answers do not have to be correct for this test - there simply just needs to be an integer number received and added to the list @player.answers
with the following method in class Player
这些问题具有整数答案,并且对于该测试,答案不一定是正确的-仅需要接收一个整数,并使用class Player
的以下方法将其添加到@player.answers
列表中
def add_answer(answer)
@answers << answer
end
How can I simulate user input to the gets.chomp
of QuestionList.ask_all
when unit testing the method as so: 在对方法进行单元测试时,如何模拟用户对QuestionList.ask_all
的gets.chomp
的输入:
class QuestionListTest < Test::Unit::TestCase
def setup
...
end
def test_ask_all
#unit test for 'QuestionList.ask_all' here
end
end
ask_all
to be input-agnostic: 1.修改ask_all
以使其与输入无关: def ask_all
@questions.each do |question|
question.ask
@player.add_answer(question.retrieve_answer)
end
end
Question
class to have retrieve_answer
method: 2.修改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 to “ask questions” not interactively: 3.模拟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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.