开发者

Testing approach - Ruby/RSpec vs Java/Mockito

I'm trying to write some code like the example shown below, but in Java instead of Ruby and Mockito instead of RSpec.

require 'rubygems'
require 'rspec'

class MyUti开发者_JAVA百科ls
  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

In RSpec I can stub File.new, but I don't think I can do this in Mockito?

Should I be using a factory to create the File objects instead, inject the factory as a dependency, and then stub that factory for the tests?


This SO answer includes mocking the File class with Mockito, perhaps it will help.


Yes, you need to inject something. Whether its a factory to create the files or the files themselves, its up to you. Once you do that, you can mock the factory in your tests.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜