【问题标题】:Testing approach - Ruby/RSpec vs Java/Mockito测试方法 - Ruby/RSpec vs Java/Mockito
【发布时间】:2011-06-14 17:18:37
【问题描述】:

我正在尝试编写一些代码,如下所示,但使用 Java 而不是 Ruby 和 Mockito 而不是 RSpec。

require 'rubygems'
require 'rspec'

class MyUtils
  def self.newest_file(files)
    newest = nil
    files.each do |file|
      if newest.nil? || (File.new(file).mtime > File.new(newest).mtime)
        newest = file
      end
    end
    newest
  end
end

describe MyUtils do
  it "should return the filename of the file with the newest timestamp" do
    file_a = mock('file', :mtime => 1000)
    file_b = mock('file', :mtime => 2000)
    File.stub(:new).with("a.txt").and_return(file_a)
    File.stub(:new).with("b.txt").and_return(file_b)
    MyUtils.newest_file(['a.txt', 'b.txt']).should == 'b.txt'
  end
end

在 RSpec 中我可以存根 File.new,但我认为我不能在 Mockito 中做到这一点?

我是否应该使用工厂来创建 File 对象,将工厂作为依赖项注入,然后为测试存根该工厂?

【问题讨论】:

    标签: java ruby unit-testing rspec mockito


    【解决方案1】:

    This SO answer 包括使用 Mockito 模拟 File 类,也许它会有所帮助。

    【讨论】:

      【解决方案2】:

      是的,你需要注入一些东西。无论是创建文件的工厂还是文件本身,都由您决定。一旦你这样做了,你就可以在你的测试中模拟工厂。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多