有webservice参与的系统的单元测试, 使用mock object (二)

前天写了文章: [url="http://sg552.iteye.com/blog/1604010"]有webservice参与的系统的单元测试,最好使用mock object[/url]

如果某个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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值