如何在 MiniTest 中使用 assert_equal 比较数组中的所有元素

How to compare all of the elements in an array using assert_equal in MiniTest

我正在比较数组中的值,但是当条件失败时,它会退出。这里我想比较数组的所有元素,不管通过与否:

val.each do | x |
    #assert_equal 48000.00, x
    assert(48000.00 == x, message = " :Pass")
end

假设数组大小为 20。无论通过或失败条件如何,它都应该迭代 20 次,并且应该提出断言。

在我回答你的问题之前:

问题听起来'wrong',如果测试失败,你为什么要继续? 我的印象是,对测试逻辑有更深的误解。也许你可以提供更多信息,看看你在这个问题背后有什么问题。

这是针对您的问题的完整 MWE:

class TestArray < MiniTest::Test
  VAL = [
    48000.0,
    48000.0,
    3,
    48000.0,
  ]

  def test_orig
    VAL.each do | x |
      assert(48000.00 == x, message = " :Pass")
    end
  end

这将测试数组中的所有条目是否都是 48000.0。您可以使用以下方法进行类似的测试:

    def test_array #expects exact 4 entries.
      assert_equal([48000.00,48000.00,48000.00,48000.00], VAL, message = " :Pass")
    end
    def test_array_2 #flexible number of entries
      assert_equal([48000.00] * VAL.size, VAL, message = " :Pass")
    end
    def test_array_uniq
      assert_equal([48000.00], VAL.uniq, message = " :Pass")
    end

    def test_diff
      assert_equal([], VAL - [48000.0], 'Entries not 48000.0 found')
    end

你会得到所有不等于 48000.0 的条目。

但是还有一个问题: 如果测试失败,你为什么要继续?

测试在第一次失败后停止。所以唯一的可能性是在其自己的测试例程中对每个值进行测试:

  class TestArray < MiniTest::Test
    VAL = [
      48000.0,
      48000.0,
      3,
      48000.0,
    ]
    VAL.each_with_index do |val,i|
      define_method :"test_single_value_#{i+1}" do
        assert(48000.00 == val, message = "Diff for entry %i" % [i+1])
      end
    end
  end

代码为数组中的每个条目生成一个测试。但是要获得这种测试可能性,必须在测试 运行 之前知道 VAL。所以这可能不符合您的需要。