SlideShare une entreprise Scribd logo
1  sur  37
TESTING WITH MOCKS
                       Macon Pegram
  Blog: http://blogs.captechconsulting.com/blog/author/Macon%20Pegram
         Code: https://github.com/mpegram3rd/testing-with-mocks
SOUND FAMILIAR?

I’d rather not change that function

This defect keeps coming back

It’s impossible to unit test our project

The backend/database is not available

Setting up my test environment takes too long

I have a testing specific Spring context
UNIT TESTING:
        WHY BOTHER?
Detect / Avoid defects

Validate Bug Fixes

Refactor without hesitation

Forces you to think about the
design

Keeps you out of the
debugger
WHAT DO WE TEST?

Testing State

  Does it have the expected values after execution?

  Usually via “assertXXX”

Verifying Behavior

  Did the Method Under Test do what I expected?
OBSTACLES TO
          TESTING
Method under test:

  Has void return type

  Runs slow

  Has complicated dependencies (IE: EJB,
  Servlet APIs, Persistence APIs)

Hard to Create scenarios (Network Exception)
TYPICAL SOLUTIONS


Run Integration Tests

In container testing

Roll your own “stub”

Don’t test
DON’T BE THESE GUYS
TERMINOLOGY
test double - pretend object used for testing (encompasses
all of the below)

dummy - object passed around but not used

fake - simple working implementation of a dependency

stub - canned answers to calls within tests.

mock - objects pre-programmed with expectations.

  Used to verify “behavior”
                                     http://xunitpatterns.com/Test%20Double.html
STUB VS. MOCK
Stubs

  Preserve and test state

  You write the
  implementations.

Mocks

  Simulate Behavior

  Validate behavior
BEHAVIOR MATTERS

How many of you have
worked with a system like
this?

How many of you have
seen a method like this?

Did you test it?

Why not?
WHY MOCK:
              ISOLATION

Application is complex

Real object may be slow

Real object is difficult to setup

Writing isolated tests is hard
WHY MOCK: PROJECT
  CONSTRAINTS

Real implementation not available

  3rd party code

  Not yet developed

Limited time for test development

Fluid Requirements
MOCKS MAKE YOU
        THINK

I have to create a lot of mocks to test.

  Class / method has too many
  responsibilities?

My Mocks need mocks

  Is the method too dependent on
  internal details?
MOCKS MAKE YOU
         THINK

I can’t mock that dependency

  Does your class have tightly bound
  dependencies, instead of dependency
  injection?

  Are statics being used?
MOCKRUNNER

Does not require a container!

Supports JavaEE 1.3 - 5

  Servlets, filters, tags, JNDI, JMS, JDBC, EJBs

  Does not support EJB 3.0

Supports Struts 1.1 - 1.3

Manual Dependency Management :-(
SOAP-UI “MOCKS”
Generate web service stub from WSDL

  Note: This is a stub.. not a mock!

Use Groovy to script responses

Export as WAR file.

  These seem to work well for testing/code validation

  Does not hold up well under extended load!
EASYMOCK
The original dynamic mocking framework.

Active development

v3.0 added many features that addressed it’s shortcomings
when compared with Mockito.

  Extend EasyMockSupport (replayAll(), verifyAll())

Hamcrest argument matchers via bridge library

Good documentation
MOCKITO

Next Generation mocking framework

Already supports Hamcrest for argument matchers.

No replay

Claims to produce more “readable” (BDD style) code and
failures

Great documentation with examples
EASYMOCK VS
             MOCKITO
Easymock

  All interactions must be set as expectations

  Explicit “replay” step

Mockito

  Mocks are “nice” by default (verify what you want)

  No replay
POWERMOCK


Extends EasyMock and Mockito

Uses custom classloader

Mock: static methods, constructors, final methods/classes,
and private methods
ASIDE: HAMCREST

Library of Matchers

  contains(), closeTo(), endsWith(), equalTo(),
  typeCompatibleWith()

Makes Assertions and Mock argument matchers more
literate

Works directly with Mockito argument matchers

EasyMock supported via a bridge Matcher
                                       http://code.google.com/p/hamcrest/
NICE VS STRICT MOCKS
Nice Mocks:

  Provides default behaviors/returns if
  none defined for a method

    IE: nulls for Objects, 0 for numbers

Strict Mocks:

  Undefined/expected behavior fails the
  test

  Variant: Order matters
STRICTS ARE BETTER(??)

Developer is required to understand the
method being tested

Creates the perception of a “brittle” test
case.

  This brittleness is a positive

  Failure is success!

Nice Mocks allow tests to pass when they
shouldn’t.
                        Strict Mock Semantics is the Only Way to Mock: http://bit.ly/bj4dSF
MOCK TESTING FLOW

Create your mocks

Define Expectations

Reset/Replay the Mock

Run your test

Verification
CREATE MOCKS


  Often done in @Before or setUp() method
public class AuthenticationFilterTest extends EasyMockSupport {

	 private AuthenticationFilter filter;
	 private AuthenticationProvider mockAuthProvider;
	 private FilterConfig mockFilterConfig;
	
	 @Before
	 public void setUp() throws Exception {
	 	 mockFilterConfig = createMock(FilterConfig.class);
	 	 mockAuthProvider = createMock(AuthenticationProvider.class);
	 	
	 	 filter = new AuthenticationFilter(mockAuthProvider);
	 }
....
}
SET EXPECTATIONS

Method and Input Parameters

Outcomes           expect(mockFilterConfig.getInitParameter(eq("authenticationURL")))
                   	        .andReturn(expectedURL);

                   expect(mockFilterConfig.getServletContext())
  Return values    	        .andThrow (new ServletException("Something broke!"));

                   expect(mockFilterConfig.getInitParameter(anyObject(String.class)))
                   	   	  	   .andReturn(expectedURL)
  Exceptions       	   	  	   .times(1,4);




Invocation Count
REPLAY/TEST/VERIFY
    Replay - Tell the mock you’re ready to test

    Run your Test

    Traditional Asserts and Mock Behavior Validation
// Prepare mocks for validation
replayAll();
	 	
// Execute test
filter.init(mockFilterConfig);

// Traditional JUnit Assertion (with Hamcrest Matcher)
assertThat(filter.getAuthenticationURL(),
           equalTo(expectedURL));
	 	
// Validates expected behavior of mocks occurred. If getInitParam() on the
// mockFilter did not get called this would fail.
verifyAll();
SPYS / PARTIAL
            MOCKS
Real methods on class are used unless
explicitly mocked

Useful for:

  3rd party libraries

  Interim refactoring of legacy code

The need to do this more often than not
suggests design issues in the code.
BLACK OR WHITEBOX?

Traditional Testing tests input/output of
publics

  How do you unit test a void?

Verifying branching logic in private
methods is challenging from the public
method.

Single public method calling multiple
privates can be hard to verify.
                   http://www.quora.com/Should-you-unit-test-private-methods-on-a-class
TESTABLE DESIGN
True? “Testable Design is Good Design”

  Most tools don’t support testing private methods or final
  classes.

  Should test tools govern your design?

  Should you write tests to safely refactor code or refactor
  code to be able to write tests?

Perhaps: “Good Design is always Testable”

  http://blog.jayway.com/2009/04/01/questioning-
LET’S LOOK AT SOME
CODE
Simple Mock Setup:
com.ctv.mocksamples.servlet.UserPrincipalRequestWrapperTest

Basic Behavior/Assertions:
com.ctv.mocksample.servlet.AuthenticationFilterTest

Strict vs Loose:
com.ctv.mocksample.servlet.AuthenticationFilterTest

PowerMocking Statics: com.ctv.model.UserTest

PowerMocking privates: com.ctv.model.OrderPowerMockTest
JAVA FRAMEWORKS

Mockrunner: http://mockrunner.sourceforge.net/

SOAP-UI: http://soapui.org/

EasyMock: http://easymock.org/

Mockito: http://mockito.org/http://code.google.com/p/
mockito/

Powermock: http://code.google.com/p/powermock/
.NET FRAMEWORKS

Rhino Mocks:

  http://www.ayende.com/projects/rhino-mocks.aspx

EasyMock.net

  http://sourceforge.net/projects/easymocknet/

NMock

  http://www.nmock.org/
RESOURCES
“Mocks aren’t Stubs” - Martin Fowler

  http://www.martinfowler.com/articles/mocksArentStubs.html

Questioning “testable design”

  http://blog.jayway.com/2009/04/01/questioning-testable-
  design/

“Testing the Entire Stack” - Neal Ford

  http://nealford.com/downloads/conferences/2010/
  Testing_the_Entire_Stack(Neal_Ford).pdf
RESOURCES

Java Mocking Framework Comparison

  http://www.sizovpoint.com/2009/03/java-mock-
  frameworks-comparison.html

EasyMock / Mockito Comparisons

  http://code.google.com/p/mockito/wiki/
  MockitoVSEasyMock

  http://blog.octo.com/en/easymock-facts-fallacies/
RESOURCES
xUnit concepts and definitions

  http://xunitpatterns.com/Test%20Double.html

Strict vs Nice Mocks

  Pro Strict: http://bit.ly/bj4dSF

  Design vs Maintainability:

    http://stackoverflow.com/questions/2864796/
    easymock-vs-mockito-design-vs-maintainability
PRESENTATION CODE



You can pull down the code from this presentation on
Github

  https://github.com/mpegram3rd/testing-with-mocks

Contenu connexe

Tendances

Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
Richard Paul
 
Unit testing (workshop)
Unit testing (workshop)Unit testing (workshop)
Unit testing (workshop)
Foyzul Karim
 

Tendances (20)

Testing for Android: When, Where, and How to Successfully Use Test Automation
Testing for Android: When, Where, and How to Successfully Use Test AutomationTesting for Android: When, Where, and How to Successfully Use Test Automation
Testing for Android: When, Where, and How to Successfully Use Test Automation
 
Google test training
Google test trainingGoogle test training
Google test training
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit Testing
 
2013 DevFest Vienna - Bad Tests, Good Tests
2013 DevFest Vienna - Bad Tests, Good Tests2013 DevFest Vienna - Bad Tests, Good Tests
2013 DevFest Vienna - Bad Tests, Good Tests
 
Implementing Quality on a Java Project
Implementing Quality on a Java ProjectImplementing Quality on a Java Project
Implementing Quality on a Java Project
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testing
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
 
Unit testing, principles
Unit testing, principlesUnit testing, principles
Unit testing, principles
 
Unit testing (workshop)
Unit testing (workshop)Unit testing (workshop)
Unit testing (workshop)
 
Software Testing
Software TestingSoftware Testing
Software Testing
 
Practical Test Automation Deep Dive
Practical Test Automation Deep DivePractical Test Automation Deep Dive
Practical Test Automation Deep Dive
 
Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android Applications
 
Efficient JavaScript Unit Testing, March 2013
Efficient JavaScript Unit Testing, March 2013Efficient JavaScript Unit Testing, March 2013
Efficient JavaScript Unit Testing, March 2013
 
Automated tests
Automated testsAutomated tests
Automated tests
 
Php tests tips
Php tests tipsPhp tests tips
Php tests tips
 
Unit-testing and E2E testing in JS
Unit-testing and E2E testing in JSUnit-testing and E2E testing in JS
Unit-testing and E2E testing in JS
 
Automating Tactically vs Strategically SauceCon 2020
Automating Tactically vs Strategically SauceCon 2020Automating Tactically vs Strategically SauceCon 2020
Automating Tactically vs Strategically SauceCon 2020
 
Battle of The Mocking Frameworks
Battle of The Mocking FrameworksBattle of The Mocking Frameworks
Battle of The Mocking Frameworks
 
Static Analysis: From Getting Started to Integration
Static Analysis: From Getting Started to IntegrationStatic Analysis: From Getting Started to Integration
Static Analysis: From Getting Started to Integration
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated Testing
 

En vedette (7)

Mockito (JUG Latvia)
Mockito (JUG Latvia)Mockito (JUG Latvia)
Mockito (JUG Latvia)
 
Unit testing basic
Unit testing basicUnit testing basic
Unit testing basic
 
Rc2010 alt architecture
Rc2010 alt architectureRc2010 alt architecture
Rc2010 alt architecture
 
1_mockito
1_mockito1_mockito
1_mockito
 
Intro to Mocking - DjangoCon 2015
Intro to Mocking - DjangoCon 2015Intro to Mocking - DjangoCon 2015
Intro to Mocking - DjangoCon 2015
 
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
[DevDay 2016] Real Unit Testing with mocking framework - Speaker: Phat Vu – S...
 
Big Data Processing Using Hadoop Infrastructure
Big Data Processing Using Hadoop InfrastructureBig Data Processing Using Hadoop Infrastructure
Big Data Processing Using Hadoop Infrastructure
 

Similaire à Testing w-mocks

An Introduction to unit testing
An Introduction to unit testingAn Introduction to unit testing
An Introduction to unit testing
Steven Casey
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
guest268ee8
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And Mocking
Joe Wilson
 
Coldbox developer training – session 4
Coldbox developer training – session 4Coldbox developer training – session 4
Coldbox developer training – session 4
Billie Berzinskas
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
Tricode (part of Dept)
 

Similaire à Testing w-mocks (20)

Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven Development
 
Deliver Faster with BDD/TDD - Designing Automated Tests That Don't Suck
Deliver Faster with BDD/TDD - Designing Automated Tests That Don't SuckDeliver Faster with BDD/TDD - Designing Automated Tests That Don't Suck
Deliver Faster with BDD/TDD - Designing Automated Tests That Don't Suck
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock Framework
 
An Introduction to unit testing
An Introduction to unit testingAn Introduction to unit testing
An Introduction to unit testing
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Quality
 
Unit testing - A&BP CC
Unit testing - A&BP CCUnit testing - A&BP CC
Unit testing - A&BP CC
 
Mocking with Mockito
Mocking with MockitoMocking with Mockito
Mocking with Mockito
 
Stopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under TestStopping the Rot - Putting Legacy C++ Under Test
Stopping the Rot - Putting Legacy C++ Under Test
 
Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013Building unit tests correctly with visual studio 2013
Building unit tests correctly with visual studio 2013
 
Junit_.pptx
Junit_.pptxJunit_.pptx
Junit_.pptx
 
Google mock training
Google mock trainingGoogle mock training
Google mock training
 
Software Engineering - RS3
Software Engineering - RS3Software Engineering - RS3
Software Engineering - RS3
 
A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)A la découverte des google/mock (aka gmock)
A la découverte des google/mock (aka gmock)
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMock
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best Practices
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And Mocking
 
Coldbox developer training – session 4
Coldbox developer training – session 4Coldbox developer training – session 4
Coldbox developer training – session 4
 
Testing Experience - Evolution of Test Automation Frameworks
Testing Experience - Evolution of Test Automation FrameworksTesting Experience - Evolution of Test Automation Frameworks
Testing Experience - Evolution of Test Automation Frameworks
 
Unit testing php-unit - phing - selenium_v2
Unit testing   php-unit - phing - selenium_v2Unit testing   php-unit - phing - selenium_v2
Unit testing php-unit - phing - selenium_v2
 
Automated Testing using JavaScript
Automated Testing using JavaScriptAutomated Testing using JavaScript
Automated Testing using JavaScript
 

Dernier

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Dernier (20)

Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot ModelMcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Mcleodganj Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
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
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 

Testing w-mocks

  • 1. TESTING WITH MOCKS Macon Pegram Blog: http://blogs.captechconsulting.com/blog/author/Macon%20Pegram Code: https://github.com/mpegram3rd/testing-with-mocks
  • 2. SOUND FAMILIAR? I’d rather not change that function This defect keeps coming back It’s impossible to unit test our project The backend/database is not available Setting up my test environment takes too long I have a testing specific Spring context
  • 3. UNIT TESTING: WHY BOTHER? Detect / Avoid defects Validate Bug Fixes Refactor without hesitation Forces you to think about the design Keeps you out of the debugger
  • 4. WHAT DO WE TEST? Testing State Does it have the expected values after execution? Usually via “assertXXX” Verifying Behavior Did the Method Under Test do what I expected?
  • 5. OBSTACLES TO TESTING Method under test: Has void return type Runs slow Has complicated dependencies (IE: EJB, Servlet APIs, Persistence APIs) Hard to Create scenarios (Network Exception)
  • 6. TYPICAL SOLUTIONS Run Integration Tests In container testing Roll your own “stub” Don’t test
  • 8. TERMINOLOGY test double - pretend object used for testing (encompasses all of the below) dummy - object passed around but not used fake - simple working implementation of a dependency stub - canned answers to calls within tests. mock - objects pre-programmed with expectations. Used to verify “behavior” http://xunitpatterns.com/Test%20Double.html
  • 9. STUB VS. MOCK Stubs Preserve and test state You write the implementations. Mocks Simulate Behavior Validate behavior
  • 10. BEHAVIOR MATTERS How many of you have worked with a system like this? How many of you have seen a method like this? Did you test it? Why not?
  • 11. WHY MOCK: ISOLATION Application is complex Real object may be slow Real object is difficult to setup Writing isolated tests is hard
  • 12. WHY MOCK: PROJECT CONSTRAINTS Real implementation not available 3rd party code Not yet developed Limited time for test development Fluid Requirements
  • 13. MOCKS MAKE YOU THINK I have to create a lot of mocks to test. Class / method has too many responsibilities? My Mocks need mocks Is the method too dependent on internal details?
  • 14. MOCKS MAKE YOU THINK I can’t mock that dependency Does your class have tightly bound dependencies, instead of dependency injection? Are statics being used?
  • 15. MOCKRUNNER Does not require a container! Supports JavaEE 1.3 - 5 Servlets, filters, tags, JNDI, JMS, JDBC, EJBs Does not support EJB 3.0 Supports Struts 1.1 - 1.3 Manual Dependency Management :-(
  • 16. SOAP-UI “MOCKS” Generate web service stub from WSDL Note: This is a stub.. not a mock! Use Groovy to script responses Export as WAR file. These seem to work well for testing/code validation Does not hold up well under extended load!
  • 17. EASYMOCK The original dynamic mocking framework. Active development v3.0 added many features that addressed it’s shortcomings when compared with Mockito. Extend EasyMockSupport (replayAll(), verifyAll()) Hamcrest argument matchers via bridge library Good documentation
  • 18. MOCKITO Next Generation mocking framework Already supports Hamcrest for argument matchers. No replay Claims to produce more “readable” (BDD style) code and failures Great documentation with examples
  • 19. EASYMOCK VS MOCKITO Easymock All interactions must be set as expectations Explicit “replay” step Mockito Mocks are “nice” by default (verify what you want) No replay
  • 20. POWERMOCK Extends EasyMock and Mockito Uses custom classloader Mock: static methods, constructors, final methods/classes, and private methods
  • 21. ASIDE: HAMCREST Library of Matchers contains(), closeTo(), endsWith(), equalTo(), typeCompatibleWith() Makes Assertions and Mock argument matchers more literate Works directly with Mockito argument matchers EasyMock supported via a bridge Matcher http://code.google.com/p/hamcrest/
  • 22. NICE VS STRICT MOCKS Nice Mocks: Provides default behaviors/returns if none defined for a method IE: nulls for Objects, 0 for numbers Strict Mocks: Undefined/expected behavior fails the test Variant: Order matters
  • 23. STRICTS ARE BETTER(??) Developer is required to understand the method being tested Creates the perception of a “brittle” test case. This brittleness is a positive Failure is success! Nice Mocks allow tests to pass when they shouldn’t. Strict Mock Semantics is the Only Way to Mock: http://bit.ly/bj4dSF
  • 24. MOCK TESTING FLOW Create your mocks Define Expectations Reset/Replay the Mock Run your test Verification
  • 25. CREATE MOCKS Often done in @Before or setUp() method public class AuthenticationFilterTest extends EasyMockSupport { private AuthenticationFilter filter; private AuthenticationProvider mockAuthProvider; private FilterConfig mockFilterConfig; @Before public void setUp() throws Exception { mockFilterConfig = createMock(FilterConfig.class); mockAuthProvider = createMock(AuthenticationProvider.class); filter = new AuthenticationFilter(mockAuthProvider); } .... }
  • 26. SET EXPECTATIONS Method and Input Parameters Outcomes expect(mockFilterConfig.getInitParameter(eq("authenticationURL"))) .andReturn(expectedURL); expect(mockFilterConfig.getServletContext()) Return values .andThrow (new ServletException("Something broke!")); expect(mockFilterConfig.getInitParameter(anyObject(String.class))) .andReturn(expectedURL) Exceptions .times(1,4); Invocation Count
  • 27. REPLAY/TEST/VERIFY Replay - Tell the mock you’re ready to test Run your Test Traditional Asserts and Mock Behavior Validation // Prepare mocks for validation replayAll(); // Execute test filter.init(mockFilterConfig); // Traditional JUnit Assertion (with Hamcrest Matcher) assertThat(filter.getAuthenticationURL(), equalTo(expectedURL)); // Validates expected behavior of mocks occurred. If getInitParam() on the // mockFilter did not get called this would fail. verifyAll();
  • 28. SPYS / PARTIAL MOCKS Real methods on class are used unless explicitly mocked Useful for: 3rd party libraries Interim refactoring of legacy code The need to do this more often than not suggests design issues in the code.
  • 29. BLACK OR WHITEBOX? Traditional Testing tests input/output of publics How do you unit test a void? Verifying branching logic in private methods is challenging from the public method. Single public method calling multiple privates can be hard to verify. http://www.quora.com/Should-you-unit-test-private-methods-on-a-class
  • 30. TESTABLE DESIGN True? “Testable Design is Good Design” Most tools don’t support testing private methods or final classes. Should test tools govern your design? Should you write tests to safely refactor code or refactor code to be able to write tests? Perhaps: “Good Design is always Testable” http://blog.jayway.com/2009/04/01/questioning-
  • 31. LET’S LOOK AT SOME CODE Simple Mock Setup: com.ctv.mocksamples.servlet.UserPrincipalRequestWrapperTest Basic Behavior/Assertions: com.ctv.mocksample.servlet.AuthenticationFilterTest Strict vs Loose: com.ctv.mocksample.servlet.AuthenticationFilterTest PowerMocking Statics: com.ctv.model.UserTest PowerMocking privates: com.ctv.model.OrderPowerMockTest
  • 32. JAVA FRAMEWORKS Mockrunner: http://mockrunner.sourceforge.net/ SOAP-UI: http://soapui.org/ EasyMock: http://easymock.org/ Mockito: http://mockito.org/http://code.google.com/p/ mockito/ Powermock: http://code.google.com/p/powermock/
  • 33. .NET FRAMEWORKS Rhino Mocks: http://www.ayende.com/projects/rhino-mocks.aspx EasyMock.net http://sourceforge.net/projects/easymocknet/ NMock http://www.nmock.org/
  • 34. RESOURCES “Mocks aren’t Stubs” - Martin Fowler http://www.martinfowler.com/articles/mocksArentStubs.html Questioning “testable design” http://blog.jayway.com/2009/04/01/questioning-testable- design/ “Testing the Entire Stack” - Neal Ford http://nealford.com/downloads/conferences/2010/ Testing_the_Entire_Stack(Neal_Ford).pdf
  • 35. RESOURCES Java Mocking Framework Comparison http://www.sizovpoint.com/2009/03/java-mock- frameworks-comparison.html EasyMock / Mockito Comparisons http://code.google.com/p/mockito/wiki/ MockitoVSEasyMock http://blog.octo.com/en/easymock-facts-fallacies/
  • 36. RESOURCES xUnit concepts and definitions http://xunitpatterns.com/Test%20Double.html Strict vs Nice Mocks Pro Strict: http://bit.ly/bj4dSF Design vs Maintainability: http://stackoverflow.com/questions/2864796/ easymock-vs-mockito-design-vs-maintainability
  • 37. PRESENTATION CODE You can pull down the code from this presentation on Github https://github.com/mpegram3rd/testing-with-mocks

Notes de l'éditeur

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n