带有minitest的未定义方法

带有minitest的未定义方法

本文介绍了NoMethodError:带有minitest的未定义方法`assert_equal'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在下面具有用于自动化测试的测试结构.

I have testing structure below for automation testing.

#/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时,我会收到此错误.

When I execute test class TestCalculator I receive this error.

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

当我在类TestCalculator中使用assert_equal方法时,它起作用了.但是这种方式将在将来导致较长的测试用例和冗余代码.如何在带有minitest的类调用的模块中使用断言"?是否有可能?

When I used assert_equal method in class TestCalculator it worked. But this way will cause in future long test cases and redundant code. How can I use "assertions" in module called by class with minitest? Is it possible?

推荐答案

所有问题均来自您的TestModule模块.仅当您查看所有其他代码以在上下文中理解它时,此模块的含义才清楚-这公然违反​​了封装原理.为什么值25很重要?当代码仅声明相等性而不执行任何加法时,为什么将这种方法称为test_addition?完全删除该模块.

The problems all come from your TestModule module. The meaning of this module is only clear if you look at all of the other code to understand it in context - this is a blatant violation of the principle of encapsulation. Why is the value 25 important? Why is the method called test_addition when the code is just asserting equality and not performing any addition? Remove that module entirely.

然后查看最小化文档以查看预期的用法.让Calculator做所有工作,而TestCalculator做断言:

Then look at the examples in the minitest documentation to see the intended usage. Let Calculator do all the work, while TestCalculator does the asserting:

# 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:带有minitest的未定义方法`assert_equal'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 18:59