NoMethodError:使用minitest的未定义方法`assert_equal'

时间:2014-10-14 13:05:52

标签: ruby minitest assertions

我在下面有自动化测试的测试结构。

#/project/class/Calculator.rb

require 'TestModule'
require 'MathOperation'

class Calculator
  include TestModule
  include MathOperation

  def initialize(num1, num2)
    @num1 = num1
    @num2 = num2
  end
end


#/project/methods/MathOperation.rb

module MathOperation
    def operation_addition
        addition = @num1 + @num2
        return addition
    end
end


#/project/methods/TestModule.rb

module TestModule
    def test_addition(value)
       assert_equal 25, value
    end   
end


#/project/tescases/TestCalculator.rb

require 'minitest/autorun'
require 'calculator'

class TestCalculator < Minitest::Test

  def setup
    @calc = Calculator.new(15, 10)
  end

  def test_proper_addition
    resolution = @calc.operation_addition
    @calc.test_addition(resolution)
  end
end

当我执行测试类TestCalculator时,我收到此错误。

NoMethodError: undefined method 'assert_equal' for #<Calculator:0x00000002a77518 @num1=15, @num2=10

当我在课程assert_equal中使用TestCalculator方法时,它有效。但是这种方式将导致未来很长的测试用例和冗余代码。如何在minitest类中调用的模块中使用“断言”?可能吗?

1 个答案:

答案 0 :(得分:2)

问题都来自您的TestModule模块。只有在查看所有其他代码以在上下文中理解它时,才能清楚此模块的含义 - 这是对封装原则的公然违反。为什么价值25很重要?当代码只是断言相等而不执行任何添加时,为什么该方法称为test_addition?完全删除该模块。

然后查看minitest documentation中的示例以查看预期用途。让Calculator完成所有工作,而TestCalculator执行断言:

# no testing code here, just functionality

module MathOperation
  def operation_addition
    addition = @num1 + @num2
  end
end

class Calculator
  include MathOperation

  def initialize(num1, num2)
    @num1 = num1
    @num2 = num2
  end
end

# and now we do all of the testing stuff

require 'minitest/autorun'

class TestCalculator < Minitest::Unit::TestCase
  def setup
    @calc = Calculator.new(15, 10)
  end

  def test_addition
    assert_equal 25, @calc.operation_addition
  end
end