测试方法 - Ruby/RSpec 与 Java/Mockito
我正在尝试编写一些代码,如下所示,但使用 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 对象,将工厂作为依赖项注入,然后存根该工厂以进行测试?
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 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
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这个答案包括用 Mockito 模拟 File 类,也许它会帮助。
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.