博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
有webservice参与的系统的单元测试, 使用mock object (二)
阅读量:4047 次
发布时间:2019-05-25

本文共 2136 字,大约阅读时间需要 7 分钟。

前天写了文章: [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

转载地址:http://dwuci.baihongyu.com/

你可能感兴趣的文章
IP报文格式学习笔记
查看>>
autohotkey快捷键显示隐藏文件和文件扩展名
查看>>
Linux中的进程
查看>>
学习python(1)——环境与常识
查看>>
学习设计模式(3)——单例模式和类的成员函数中的静态变量的作用域
查看>>
自然计算时间复杂度杂谈
查看>>
当前主要目标和工作
查看>>
使用 Springboot 对 Kettle 进行调度开发
查看>>
一文看清HBase的使用场景
查看>>
解析zookeeper的工作流程
查看>>
搞定Java面试中的数据结构问题
查看>>
慢慢欣赏linux make uImage流程
查看>>
linux内核学习(7)脱胎换骨解压缩的内核
查看>>
以太网基础知识
查看>>
慢慢欣赏linux 内核模块引用
查看>>
kprobe学习
查看>>
慢慢欣赏linux phy驱动初始化2
查看>>
慢慢欣赏linux CPU占用率学习
查看>>
2020年终总结
查看>>
Homebrew指令集
查看>>