前天写了文章: [url="http://sg552.iteye.com/blog/1604010"]有webservice参与的系统的单元测试,最好使用mock object[/url]
如果某个mock对象,要求模拟 POST 这样的修改数据的操作,而不是简单的GET 这样的查询,该如何做呢?
我现在使用的办法,是 使用yaml文件来存储数据,达到简单的模仿 数据库的目的。
例如:
那么,我们就可以在MockObject中引用这个 module:
对该 Mock Object的测试:
如果某个mock对象,要求模拟 POST 这样的修改数据的操作,而不是简单的GET 这样的查询,该如何做呢?
我现在使用的办法,是 使用yaml文件来存储数据,达到简单的模仿 数据库的目的。
例如:
require 'yaml'
module YamlStoreStrategy
YAML_FILE_NAME = "spec/mock_attributes.yaml"
private
def update_yaml(hash)
content = YAML.load(File.open(YAML_FILE_NAME))
content[self.class.name] = hash
File.open(YAML_FILE_NAME, 'w') { |file| file.write(content.to_yaml)}
end
def result_hash_from_yaml
content = YAML.load(File.open(YAML_FILE_NAME))[self.class.name]
return content
end
end
require 'spec_helper'
class SomeMockResource
include YamlStoreStrategy
def run_private_methods_from_module
update_yaml("blablabla" => "foo")
result_hash_from_yaml
end
end
describe SomeMockResource do
before do
@some_mock_resource = SomeMockResource.new
end
it "should run the private methods from module" do
@some_mock_resource.run_private_methods_from_module
end
it "should update_yaml , then query from yaml" do
purpose = "test if the module works"
@some_mock_resource.send(:update_yaml,{"name"=>"some resource", "purpose"=> purpose})
@some_mock_resource.send(:result_hash_from_yaml)["purpose"].should == purpose
end
end
SomeMockResource:
那么,我们就可以在MockObject中引用这个 module:
require 'spec/support/yaml_store_strategy.rb'
class MockServerSettingResource < ServerSettingResource
include YamlStoreStrategy
def find(params)
return [result_hash_from_yaml.merge(params)]
end
def create(params)
updated_hash = result_hash_from_yaml.merge(params)
update_yaml(updated_hash)
return [updated_hash]
end
end
对该 Mock Object的测试:
require 'spec_helper'
describe MockServerSettingResource do
describe "create , then query" do
it "should create settings "do
key_name = "foo"
value = "value of the key: foo"
resource = MockServerSettingResource.new
resource.create({ :name => key_name, :value => value })
result = resource.find({:name => key_name})
result[:name].should == key_name
result[:value].should == value
end
end
end