Ruby 一个测试的小例子

chenge · June 28, 2017 · 1047 hits

分享给初学测试的网友。

代码很简单,不用过多解释了。

问题 1:那个 stub 不知道是否有更简洁的写法?spec 不太会写,欢迎补充。

问题 2:就是我还是用了依赖注入,DHH 博文说不用依赖注入,举例:Time.stub(:now),不知道这里怎么做。

关于 TDD 的看法,我赞成接口层仔细测试,其他部分间接测试。


require 'minitest/autorun'
require 'minitest/mock'

class Engine; end

class Calc

  def initialize
    @engine = Engine.new
  end

  def add(x, y)
    @engine.add(x, y)
  end

  def engine=(engine)
    @engine = engine
  end

end


class TestCalc < Minitest::Test

  def test_add

    engine_stub = Minitest::Mock.new
    def engine_stub.add(x, y)
      3
    end

    c = Calc.new
    c.engine = engine_stub

    assert c.add(1, 2)==3
  end

end

No Reply at the moment.
You need to Sign in before reply, if you don't have an account, please Sign up first.