NoMethodError:未定义的方法`assert_equal”与MINITEST(NoMeth

2019-10-21 03:47发布

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

#/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? 可能吗?

Answer 1:

这些问题都来自你的TestModule模块。 该模块的意思是只有在你看所有的其他代码来了解它在上下文中的明确 - 这是公然违反封装的原则。 为什么值25重要? 为什么叫方法test_addition当代码只是主张平等和不执行任何另外? 删除模块完全。

再来看一下在实例MINITEST文档看到预期的使用情况。 让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


文章来源: NoMethodError: undefined method `assert_equal' with minitest