SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

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 AutomationTrent Peterson
 
Google test training
Google test trainingGoogle test training
Google test trainingThierry Gayet
 
An Introduction to Unit Testing
An Introduction to Unit TestingAn Introduction to Unit Testing
An Introduction to Unit TestingJoe Tremblay
 
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 TestsTomek Kaczanowski
 
Implementing Quality on a Java Project
Implementing Quality on a Java ProjectImplementing Quality on a Java Project
Implementing Quality on a Java ProjectVincent Massol
 
Understanding Unit Testing
Understanding Unit TestingUnderstanding Unit Testing
Understanding Unit Testingikhwanhayat
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing FundamentalsRichard Paul
 
Unit testing (workshop)
Unit testing (workshop)Unit testing (workshop)
Unit testing (workshop)Foyzul Karim
 
Software Testing
Software TestingSoftware Testing
Software TestingAdroitLogic
 
Practical Test Automation Deep Dive
Practical Test Automation Deep DivePractical Test Automation Deep Dive
Practical Test Automation Deep DiveAlan Richardson
 
Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android ApplicationsRody Middelkoop
 
Efficient JavaScript Unit Testing, March 2013
Efficient JavaScript Unit Testing, March 2013Efficient JavaScript Unit Testing, March 2013
Efficient JavaScript Unit Testing, March 2013Hazem Saleh
 
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 JSMichael Haberman
 
Automating Tactically vs Strategically SauceCon 2020
Automating Tactically vs Strategically SauceCon 2020Automating Tactically vs Strategically SauceCon 2020
Automating Tactically vs Strategically SauceCon 2020Alan Richardson
 
Battle of The Mocking Frameworks
Battle of The Mocking FrameworksBattle of The Mocking Frameworks
Battle of The Mocking FrameworksDror Helper
 
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 IntegrationAndrey Karpov
 
Unit Tests And Automated Testing
Unit Tests And Automated TestingUnit Tests And Automated Testing
Unit Tests And Automated TestingLee Englestone
 

Was ist angesagt? (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
 

Andere mochten auch

Mockito (JUG Latvia)
Mockito (JUG Latvia)Mockito (JUG Latvia)
Mockito (JUG Latvia)Dmitry Buzdin
 
Rc2010 alt architecture
Rc2010 alt architectureRc2010 alt architecture
Rc2010 alt architectureJasonOffutt
 
Intro to Mocking - DjangoCon 2015
Intro to Mocking - DjangoCon 2015Intro to Mocking - DjangoCon 2015
Intro to Mocking - DjangoCon 2015Excella
 
[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...DevDay.org
 
Big Data Processing Using Hadoop Infrastructure
Big Data Processing Using Hadoop InfrastructureBig Data Processing Using Hadoop Infrastructure
Big Data Processing Using Hadoop InfrastructureDmitry Buzdin
 

Andere mochten auch (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
 

Ähnlich wie Testing w-mocks

Test-Driven Development
Test-Driven DevelopmentTest-Driven Development
Test-Driven DevelopmentJohn Blum
 
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 SuckKevin Brockhoff
 
Unit testing with Spock Framework
Unit testing with Spock FrameworkUnit testing with Spock Framework
Unit testing with Spock FrameworkEugene Dvorkin
 
An Introduction to unit testing
An Introduction to unit testingAn Introduction to unit testing
An Introduction to unit testingSteven Casey
 
Assessing Unit Test Quality
Assessing Unit Test QualityAssessing Unit Test Quality
Assessing Unit Test Qualityguest268ee8
 
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 TestSeb Rose
 
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 2013Dror Helper
 
Google mock training
Google mock trainingGoogle mock training
Google mock trainingThierry Gayet
 
Software Engineering - RS3
Software Engineering - RS3Software Engineering - RS3
Software Engineering - RS3AtakanAral
 
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)Thierry Gayet
 
Mockito with a hint of PowerMock
Mockito with a hint of PowerMockMockito with a hint of PowerMock
Mockito with a hint of PowerMockYing Zhang
 
Unit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesUnit Testing Concepts and Best Practices
Unit Testing Concepts and Best PracticesDerek Smith
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And MockingJoe Wilson
 
Coldbox developer training – session 4
Coldbox developer training – session 4Coldbox developer training – session 4
Coldbox developer training – session 4Billie Berzinskas
 
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Łukasz Morawski
 
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_v2Tricode (part of Dept)
 
Automated Testing using JavaScript
Automated Testing using JavaScriptAutomated Testing using JavaScript
Automated Testing using JavaScriptSimon Guest
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
[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.pdfhans926745
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
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 MenDelhi Call girls
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
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 organizationRadu Cotescu
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
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 2024The Digital Insurer
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 

Kürzlich hochgeladen (20)

Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - 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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
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
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
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
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 

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

Hinweis der Redaktion

  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