如何在循环中对stdin中的stdin进行单元测试?

时间:2016-11-17 11:49:56

标签: ruby unit-testing user-input stdin

我在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

1 个答案:

答案 0 :(得分:1)

1。将ask_all修改为输入不可知:

def ask_all
    @questions.each do |question|
        question.ask
        @player.add_answer(question.retrieve_answer)
    end
end

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

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
相关问题