SlideShare uma empresa Scribd logo
1 de 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

Mais conteúdo relacionado

Mais procurados

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
 

Mais procurados (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
 

Destaque

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
 

Destaque (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
 

Semelhante a 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
 

Semelhante a 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
 

Último

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfOrbitshub
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
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 REVIEWERMadyBayot
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMKumar Satyam
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businesspanagenda
 
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.pptxRemote DBA Services
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...apidays
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
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...Jeffrey Haguewood
 
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, ...apidays
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKJago de Vreede
 
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 ModelDeepika Singh
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
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 DevelopersWSO2
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 

Último (20)

Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
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
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
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
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
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...
 
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, ...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
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
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
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
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 

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

Notas do Editor

  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