【问题标题】:How to write test case for program exit如何编写程序退出的测试用例
【发布时间】:2014-07-22 21:43:08
【问题描述】:

我有一个代码 sn-p,当我使用gets 接收来自STDINexit 输入时,我将在其中终止程序。我如何编写相同的 rspec 测试用例。

下面是代码sn-p。

class CommandProcessor
    attr_accessor :input
    attr_accessor :operation
    def parser
        while true
            input = gets.chomp
            operation = input.split(' ')[0]
            param = input.split(' ')[1]
            if operation.eql? 'exit'
                exit
            end
        end
    end
end

以下是我的尝试。

describe "CommandProcessor" do
    it "will exit on input exit" do
        cmd = CommandProcessor.new
        cmd.parser
        expect { it_will_exit }.raise_exception(SystemExit) 
    end
end

更新

我之前尝试过 Leonid Mirsky 的方法,得到了这个错误:

lib/calculator.rb:37:in `parser': undefined method `chomp' for nil:NilClass (NoMethodError)

【问题讨论】:

标签: ruby rspec


【解决方案1】:

您可以在 cmd 对象本身上存根 gets 方法。

使用以下规范代码:

describe "CommandProcessor" do
  it "will exit on input exit" do
    cmd = CommandProcessor.new
    cmd.stub(:gets) {"exit\n"}
    expect { cmd.parser }.to raise_error SystemExit
  end
end

【讨论】:

  • gets.chomp 更改为 gets.to_s.chomp 以避免该错误。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多