`
sg552
  • 浏览: 613056 次
  • 性别: Icon_minigender_1
  • 来自: 北京
博客专栏
47437293-94b9-3b04-9152-8971c7580049
白手起家学习使用Flex
浏览量:18443
社区版块
存档分类
最新评论

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

阅读更多
前天写了文章: 有webservice参与的系统的单元测试,最好使用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
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics