繁体   English   中英

在Ruby中进行测试-如何编写比较数组中子数组的测试?

[英]Testing in Ruby - how to write a test that compares sub-arrays in an array?

我一直在编写一系列比较字符串,数组等的小型Ruby程序。我目前正在学习如何为我的方法编写小型单元测试。 我已经能够编写对字符串执行函数的简单测试,但是当涉及到更困难的测试时,例如对数组执行函数的测试,我一无所知。 如果有人可以帮助我解决当前的问题,我将不胜感激。

假设我的文件夹中有三个文件:program.rb,plant_methods.rb和tc_plant_methods.rb

这是plant_methods.rb中的内容。 它包含一个带有两个可用方法的类。 plant_sort方法循环遍历数组数组,并根据数组中的第一项将它们按字母顺序排列。

class Plant_Methods
  def initialize
  end

  def self.plant_sort(array) 
    array.sort! { |sub_array1, sub_array2|
      sub_array1[0] <=> sub_array2[0] }
  end
end

这是program.rb中的代码

require_relative 'plant_methods'

plant_array = [['Rose', 'Lily', 'Daisy'], ['Willow', 'Oak', 'Palm'], ['Corn', 'Cabbage', 'Potato']]

Plant_Methods.plant_sort(plant_array)

print plant_array

这是运行program.rb时的输出。 您可以按照每个第一个元素的字母顺序排列每个子数组:

[["Corn", "Cabbage", "Potato"], ["Rose", "Lily", "Daisy"], ["Willow", "Oak", "Palm"]]

现在,我的问题是:如何为此编写单元测试? 这是我的tc_plant_methods.rb文件中当前的内容:

require_relative "plant_methods"
require_relative "program"
require "test/unit"

class Test_Plant_Methods < Test::Unit::TestCase

  def test_plant_sort
    assert_equal("[["Gingko", "Beech"], ["Rice", "Wheat"], ["Violet", "Sunflower"]]", Plant_Methods.new([["Violet", "Sunflower"], ["Gingko", "Beech"], ["Rice", "Wheat"]]).plant_sort([["Violet", "Sunflower"], ["Gingko", "Beech"], ["Rice", "Wheat"]]))
  end

end

尝试运行单元测试时,我总是收到错误消息。 我在这里做错什么了吗? 这是我尝试运行测试时出现的第一个错误:

tc_plant_methods.rb:8: syntax error, unexpected tCONSTANT, expecting ')'

该错误是由于在表达式中不正确使用双引号引起的,

"[["Gingko", "Beech"], ["Rice", "Wheat"], ["Violet", "Sunflower"]]"

在这里,“ [[”标记字符串[[

为什么不对数组的相等性进行断言而不是对字符串的相等性进行断言?

assert_equal([["Gingko", "Beech"], ["Rice", "Wheat"], ["Violet", "Sunflower"]], Plant_Methods.new([["Violet", "Sunflower"], ["Gingko", "Beech"], ["Rice", "Wheat"]]).plant_sort([["Violet", "Sunflower"], ["Gingko", "Beech"], ["Rice", "Wheat"]]))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM