SlideShare a Scribd company logo
1 of 41
Download to read offline
使 用 Mock object
 进 行 测 试
    张   元   一
什么是Mock object?
wikipedia

Mock object 是面向对象编程中
,对真实对象的行为以可控的
方式进行模拟的一种虚拟对象
汽车碰撞测试中的模型人
为什么需要Mock object?
1.降低代码耦合
一个改动导致大量测试失败
def test_create
  post :create, :user =>
     {:name => 'test'}
end

def test_update
  put :update, :user =>
     {:name => 'new'}
end
add_column :first_name
add_column :last_name
remove_column :name



      挂了!
2. 人生短暂,珍惜时间
不要重复测试


A测试例中已经测试过的代
码没必要再在B测试例中进
行测试,尤其是这些代码很耗
时
# post_test.rb
def test_should_create_post
  post = Post.new(...)
  assert post.valid?
end

class post
  validates_presence_of :xxx
end
# posts_controller_test.rb
def test_should_create_post
  post :create,
          :post => {...}
  ...
end
# posts_controller.rb
def create
  post = Post.new(params[:post])
  if post.save
    ...
end



          重复了!
3.让自己更轻松
等待是人世间最痛苦的事情之一,
尤其是你苦苦等待的结果居然是:


   Failure!
如何使用Mock object?
Mocha, Flex Mock or RSpec
Mocha
@post = mock(“post”)

@post = Post.new
@post = mock(“post”)
@post.digg


#<Mock:post>.digg -
expected calls: 0, actual
calls: 1
@post.expects(:digg)


@post.instance_eval {
  def digg
    ...
  end
}
def test_xxx
  @post.expects(:digg)
end


#<Mock:post>.digg -
expected calls: 1, actual
calls: 0
@post.expects(:digg).once
at_least(min)
at_least_once
at_most(max)
at_most_once
never
times(num)
if @post.digg # nil
  ...
else
  ...
end
@post.expects(:digg)
    .returns(true)

@post.expects(:digg)
    .raises(exception)
@post.digg(@blocked) # false
@post.digg(@unblocked) # true

@post.expects(:digg)
   .with(any_of(User.blocked))
   .returns(false)

@post.expects(:digg)
.with(any_of(User.unblocked))
   .returns(true)
all_of
any_of
anything
has_entry(key, value)
has_key(key)
has_value(value)
includes(item)
instance_of(klass)
kind_of(klass)
regexp_matches(regexp)
@post.expects(:method)
    .at_least(0)
@post.expects(:method)
    .at_least(0)
    .returns(:result)

@post.stubs(:method)
@post.stubs(:method =>
                :result)
@post = stub_everything('post'
    :method => :result)



@post.method1 # nil
@post.method2 # nil
@post.method # :result
Mocha on Rails
def test_create
  post :create, :user =>
     {:name => 'test'}
end

add_column :first_name
add_column :last_name
remove_column :name
def test_should_create_user
  Post.expects(:new)
          .returns(@post)
  @post.expects(:save)
          .returns(true)

  post :create, :user => {}
  assert_redirect_to
          user_path(@user)
end
告别Fixture!
# teachers_students.yml
       one:
         teacher_id: 1
不够直观     student_id: 1
       two:
         teacher_id: 1
浪费时间     student_id: 2
       three:
         teacher_id: 2
         student_id: 3
def setup
  @user = User.new(:name=>'test')
  @post1 =
Post.new(:title=>'post1')
end
def test_should_show_post
  User.expects(:find)
          .returns(@user)
  @user.posts.expects(:find)
          .returns(@post1)

  get :show, :id=>1, :user_id=>1
  assert_response :success
end
RSpec
it “should create a new user” do
  User.should_receive(:new)
          .and_return(@user)
  User.stub!(:save)
          .and_return(true)

  post :create, :user => {}
  response.should

redirect_to(user_path(@user))
end
Flex Mock?



同样的思想,不同的实现!
问题?
谢谢!

More Related Content

What's hot

Não alimente os trolls: JavaScript é bonito - FrontInSM 2015
Não alimente os trolls: JavaScript é bonito - FrontInSM 2015Não alimente os trolls: JavaScript é bonito - FrontInSM 2015
Não alimente os trolls: JavaScript é bonito - FrontInSM 2015
Rafael Specht da Silva
 
Select * from internet
Select * from internetSelect * from internet
Select * from internet
markandey
 
Analisis Forense Memoria RAM
Analisis Forense Memoria RAMAnalisis Forense Memoria RAM
Analisis Forense Memoria RAM
Conferencias FIST
 

What's hot (20)

Delete statement in PHP
Delete statement in PHPDelete statement in PHP
Delete statement in PHP
 
Meta Programming with JavaScript
Meta Programming with JavaScriptMeta Programming with JavaScript
Meta Programming with JavaScript
 
Embracing Capybara
Embracing CapybaraEmbracing Capybara
Embracing Capybara
 
Não alimente os trolls: JavaScript é bonito - FrontInSM 2015
Não alimente os trolls: JavaScript é bonito - FrontInSM 2015Não alimente os trolls: JavaScript é bonito - FrontInSM 2015
Não alimente os trolls: JavaScript é bonito - FrontInSM 2015
 
Select * from internet
Select * from internetSelect * from internet
Select * from internet
 
JBoss Fuse - Fuse workshop Error Handling
JBoss Fuse - Fuse workshop Error HandlingJBoss Fuse - Fuse workshop Error Handling
JBoss Fuse - Fuse workshop Error Handling
 
Opensocial Codelab
Opensocial CodelabOpensocial Codelab
Opensocial Codelab
 
2013-06-25 - HTML5 & JavaScript Security
2013-06-25 - HTML5 & JavaScript Security2013-06-25 - HTML5 & JavaScript Security
2013-06-25 - HTML5 & JavaScript Security
 
Ajax On S2 Odp
Ajax On S2 OdpAjax On S2 Odp
Ajax On S2 Odp
 
[PyConZA 2017] Web Scraping: Unleash your Internet Viking
[PyConZA 2017] Web Scraping: Unleash your Internet Viking[PyConZA 2017] Web Scraping: Unleash your Internet Viking
[PyConZA 2017] Web Scraping: Unleash your Internet Viking
 
Java script events
Java script  eventsJava script  events
Java script events
 
JavaScript Operators
JavaScript OperatorsJavaScript Operators
JavaScript Operators
 
Functional testing with capybara
Functional testing with capybaraFunctional testing with capybara
Functional testing with capybara
 
10. CodeIgniter vederea inregistrarilor
10. CodeIgniter vederea inregistrarilor10. CodeIgniter vederea inregistrarilor
10. CodeIgniter vederea inregistrarilor
 
Programming JNI
Programming JNIProgramming JNI
Programming JNI
 
Growing jQuery
Growing jQueryGrowing jQuery
Growing jQuery
 
Analisis Forense Memoria RAM
Analisis Forense Memoria RAMAnalisis Forense Memoria RAM
Analisis Forense Memoria RAM
 
Clearance: Simple, complete Ruby web app authentication.
Clearance: Simple, complete Ruby web app authentication.Clearance: Simple, complete Ruby web app authentication.
Clearance: Simple, complete Ruby web app authentication.
 
Pemrograman Web 9 - Input Form DB dan Session
Pemrograman Web 9 - Input Form DB dan SessionPemrograman Web 9 - Input Form DB dan Session
Pemrograman Web 9 - Input Form DB dan Session
 
My Family
My FamilyMy Family
My Family
 

Similar to Testing with mock object

Ruby on Rails 2.1 What's New Chinese Version
Ruby on Rails 2.1 What's New Chinese VersionRuby on Rails 2.1 What's New Chinese Version
Ruby on Rails 2.1 What's New Chinese Version
Libin Pan
 
4. Метапрограмиране
4. Метапрограмиране4. Метапрограмиране
4. Метапрограмиране
Stefan Kanev
 
技術トレンディセミナー フレームワークとしてのTrac
技術トレンディセミナー フレームワークとしてのTrac技術トレンディセミナー フレームワークとしてのTrac
技術トレンディセミナー フレームワークとしてのTrac
terada
 
事件模型探究
事件模型探究事件模型探究
事件模型探究
ematrix
 

Similar to Testing with mock object (20)

Ruby on Rails 2.1 What's New Chinese Version
Ruby on Rails 2.1 What's New Chinese VersionRuby on Rails 2.1 What's New Chinese Version
Ruby on Rails 2.1 What's New Chinese Version
 
Chinaonrails Rubyonrails21 Zh
Chinaonrails Rubyonrails21 ZhChinaonrails Rubyonrails21 Zh
Chinaonrails Rubyonrails21 Zh
 
T1
T1T1
T1
 
Ajax и будущее Java Script
Ajax и будущее Java ScriptAjax и будущее Java Script
Ajax и будущее Java Script
 
4. Метапрограмиране
4. Метапрограмиране4. Метапрограмиране
4. Метапрограмиране
 
php part 2
php part 2php part 2
php part 2
 
Ruby on Rails Tutorial Part I
Ruby on Rails Tutorial Part IRuby on Rails Tutorial Part I
Ruby on Rails Tutorial Part I
 
技術トレンディセミナー フレームワークとしてのTrac
技術トレンディセミナー フレームワークとしてのTrac技術トレンディセミナー フレームワークとしてのTrac
技術トレンディセミナー フレームワークとしてのTrac
 
Theme Development and Customization
Theme Development and CustomizationTheme Development and Customization
Theme Development and Customization
 
DOSUG Intro to JQuery JavaScript Framework
DOSUG Intro to JQuery JavaScript FrameworkDOSUG Intro to JQuery JavaScript Framework
DOSUG Intro to JQuery JavaScript Framework
 
Reloaded
ReloadedReloaded
Reloaded
 
事件模型探究
事件模型探究事件模型探究
事件模型探究
 
Why Our Code Smells
Why Our Code SmellsWhy Our Code Smells
Why Our Code Smells
 
Routing System In Symfony 1.2
Routing System In Symfony 1.2Routing System In Symfony 1.2
Routing System In Symfony 1.2
 
Jslunch6
Jslunch6Jslunch6
Jslunch6
 
Spring Framework勉強会
Spring  Framework勉強会Spring  Framework勉強会
Spring Framework勉強会
 
Sphinx on Rails
Sphinx on RailsSphinx on Rails
Sphinx on Rails
 
HCI: Design Process
HCI: Design ProcessHCI: Design Process
HCI: Design Process
 
Ontology-based Content Management System (ICIM 2008)
Ontology-based Content Management System (ICIM 2008)Ontology-based Content Management System (ICIM 2008)
Ontology-based Content Management System (ICIM 2008)
 
Why Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary ThingWhy Hacking WordPress Search Isn't Some Big Scary Thing
Why Hacking WordPress Search Isn't Some Big Scary Thing
 

Recently uploaded

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 

Recently uploaded (20)

08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 

Testing with mock object