加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

单元测试ruby命令行应用程序的代码 – 如何模拟/传递ARGV

发布时间:2020-12-17 04:16:52 所属栏目:百科 来源:网络整理
导读:我有一个命令行应用程序,它使用thor来处理选项的解析.我想用test-unit和/或minitest对代码进行命令行功能的单元测试. 我似乎无法弄清楚如何确保ARGV数组(通常会从命令行保存选项)保存我的测试选项,以便可以针对代码测试它们. 具体应用代码: # myapp/command
我有一个命令行应用程序,它使用thor来处理选项的解析.我想用test-unit和/或minitest对代码进行命令行功能的单元测试.

我似乎无法弄清楚如何确保ARGV数组(通常会从命令行保存选项)保存我的测试选项,以便可以针对代码测试它们.

具体应用代码:

# myapp/commands/build.rb
require 'thor'

module Myapp
  module Commands

    # Define build commands for MyApp command line
    class Build < Thor::Group
      include Thor::Actions

      build = ARGV.shift
      build = aliases[build] || build

      # Define arguments and options
      argument :type
      class_option :test_framework,:default => :test_unit

      # Define source root of application
      def self.source_root
        File.dirname(__FILE__)
      end

      case build

      # 'build html' generates a html
      when 'html'

        # The resulting html
        puts "<p>HTML</p>"
      end
    end
  end
end

可执行文件

# bin/myapp

测试文件

# tests/test_build_html.rb

require 'test/unit'
require 'myapp/commands/build'


class TestBuildHtml < Test::Unit::TestCase
  include Myapp::Commands

  # HERE'S WHAT I'D LIKE TO DO
  def test_html_is_built

    # THIS SHOULD SIMULATE 'myapp build html' FROM THE COMMAND-LINE
    result = MyApp::Commands::Build.run(ARGV << 'html')
    assert_equal result,"<p>HTML</p>"
  end

end

我已经能够在测试类中将数组传递给ARGV,但是一旦我调用Myapp / Commands / Build,ARGV似乎是空的.我需要确保ARGV数组持有’build’和’html’,以便Build命令工作并通过.

解决方法

设置ARGV并避免警告的最简单方法是:
ARGV.replace your_argv

发现于http://apidock.com/ruby/Test/Unit/setup_argv/class

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读