我正在尝试编写一些如下所示示例的代码,但是使用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对象,将工厂作为依赖项注入,然后对该工厂进行测试存根?

最佳答案

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

10-07 12:00