SlideShare a Scribd company logo
1 of 42
Unit Testing in Java




                 Testing for Developers



                                    Guy Davis
                                    9/18/2006
    01/10/2009
Objectives

        Understand JUnit4 test framework
    
        Learn unit testing methodology
    
            What, when, and how to test…
        –

        Design app for testability and maintainability
    
        Write maintainable unit tests
    
            Assertions, Stubbing, Fixtures
        –

        Contrast with functional/acceptance testing
    



2                         01/10/2009
Contents

        Introduction to Unit Testing
    
        Unit Testing Methodology
    
        Test Style and Maintainability
    
        JUnit Assertions
    
        Test Fixture Setup
    
        Testing Indirect Inputs and Outputs
    
        Design for Testability
    
        Testing Legacy Systems
    
        Data-driven Testing
    


3                        01/10/2009
Why Test?

        Why Developer Testing?
    
            Can’t QA “test quality into the product”?
        –

        Test terminology
    
            Black-box and white-box tests
        –
            Unit, Component, System
        –
            Integration, Functional, Acceptance
        –
            Regression, Performance, Destructive
        –

        Question: Why automate tests?
    


4                         01/10/2009           Section: Introduction to Unit Testing
Compared to Functional Testing

        What is functional testing?
    
            Tests the requirements, not the design.
        –
            Tests at the system level, not the unit (class).
        –
                 Involves many interacting components
             

            Typically requires more setup to test
        –
                 Functional tests are more state-dependent
             

            Automated functional tests avoid the GUI
        –
                 Test the business processes and logic
             




5                             01/10/2009             Section: Introduction to Unit Testing
JUnit Test Framework

        Concepts in JUnit:
    
            Test Method: single test
        –
            Test Case: group of test methods
        –

            Test Suite: group of test cases
        –
            Test Fixture: supporting objects
        –

        Recently updated to JUnit4
    
            Uses assertions from JDK 1.5
        –




6                                              Section: Introduction to Unit Testing
                         01/10/2009
Running JUnit, Viewing Results

        Running JUnit in Eclipse
    
            Run, Debug
        –
            Single/All
        –

        Running JUnit from Ant
    
            Unit, Integration, All
        –

        Build system test results
    
        Code coverage report
    



7                          01/10/2009   Section: Introduction to Unit Testing
Test Execution

        Steps in a test
    
            Setup test fixtures: @BeforeClass, @Before
        –
            Exercise the system under test (SUT)
        –

            Verify the expected outcomes
        –
            Cleanup: @AfterClass, @After
        –

        Two possible outcomes:
    
            Pass or Fail
        –




8                                           Section: Introduction to Unit Testing
                           01/10/2009
Verifying Outcomes

        Use assertXYZ(“comment”, expected, actual)
    
            Use most appropriate assert available
        –
            Add descriptive comment as first argument
        –

        Test exceptional outcomes
    
            @Test(expected = IllegalArgumentException.class)
        –

            Use fail(“Should never …”) method
        –

        Performance assertions
    
            @Test(timeout=500)
        –


9                                                Section: Introduction to Unit Testing
                           01/10/2009
Finding Test Conditions

         What are the inputs to SUT?
     
             Method arguments
         –
             System state
         –

             External data and files
         –

         What are the outputs of SUT?
     
             Direct outputs: Returned values, exceptions
         –
             Side effects: state of system and its objects
         –




10                                              Section: Unit Testing Methodology
                           01/10/2009
Finding Test Cases

         Boundary Values
     
             For -256, -1, 0, 1, 255 for 8-bit integers
         –

         Cardinality Choices
     
             0, 1, 2
         –
             Null, “”, “Some String”
         –

         Failure cases
     
             Nulls and other invalid inputs
         –




11                                                Section: Unit Testing Methodology
                            01/10/2009
Test Granularity

         How many tests are needed?
     
             Enough to cover all test conditions
         –
             If code coverage is 100%: Are you done?
         –

         How many conditions per test?
     
             1:1 is ideal; easier to determine exact failure
         –

             Not so small it creates unnecessary overhead
         –




12                                              Section: Unit Testing Methodology
                           01/10/2009
Assertions

         Goals for assertions:
     
             Tests as documentation
         –
             Avoid test code duplication
         –

             Reduce likelihood of test errors; simplicity
         –

         Assertion patterns:
     
             Expected Objects
         –
             Guard Assertions
         –

             Custom Asserts
         –


13                                                     Section: JUnit Assertions
                            01/10/2009
Terminology

         Clean Slate
     
             Each test method does own setup
         –
             Independent and cohesive
         –

         Standard Test Fixture
     
             Assumes standard environment for each
         –

         Shared Test Fixture
     
             Standard environment shared by all tests
         –




14                                                Section: Test Fixture Setup
                          01/10/2009
Practices

         Extract common fixtures into setUp()
     
             Avoid code duplication for test setup
         –

         Write creation methods i.e. createPerson()
     

         Place common cleanup into tearDown()
     
             Better than many finally blocks in tests
         –

         Use inner classes (named & anonymous)
     
             Avoids test code in production classes
         –

         Avoid hard-coded data in tests-> use constants
     



15                                                      Section: Test Fixture Setup
                              01/10/2009
What is a good test?

         Self-checking                Unit testing Patterns
                              
                                          Single glance readable
         Repeatable                   –
     
                                          Single condition test
                                      –
         Robust
     
                                          Declarative style
                                      –
         Complete
     
                                          Clean-slate setup
                                      –
         Efficient
                                         Custom assertions
                                      –
                                          Stub out dependencies
         Specific                     –
     
                                          Consistent naming
                                      –
         Reviewed
     
                                          Back to front test coding
                                      –
                                          Test-driven development
                                      –



16                                                  Section: Test Style and Maintainability
                         01/10/2009
Indirect Inputs




17                             Section: Testing Indirect Conditions
                  01/10/2009
Indirect Inputs

         Types of inputs:
     




17                                  Section: Testing Indirect Conditions
                       01/10/2009
Indirect Inputs

         Types of inputs:
     
             Returned values internal to SUT
         –




17                                             Section: Testing Indirect Conditions
                          01/10/2009
Indirect Inputs

         Types of inputs:
     
             Returned values internal to SUT
         –
             Updateable parameters
         –




17                                             Section: Testing Indirect Conditions
                          01/10/2009
Indirect Inputs

         Types of inputs:
     
             Returned values internal to SUT
         –
             Updateable parameters
         –

             Internal exception handling
         –




17                                             Section: Testing Indirect Conditions
                          01/10/2009
Indirect Inputs

         Types of inputs:
     
             Returned values internal to SUT
         –
             Updateable parameters
         –

             Internal exception handling
         –

         How do we test this?
     




17                                             Section: Testing Indirect Conditions
                          01/10/2009
Indirect Inputs

         Types of inputs:
     
             Returned values internal to SUT
         –
             Updateable parameters
         –

             Internal exception handling
         –

         How do we test this?
     
             Mock Objects (a.k.a. Stubs)
         –




17                                             Section: Testing Indirect Conditions
                          01/10/2009
Stubbing Strategy
          Test creates stub
     1.
          Stub provided to SUT               Test
     2.

          SUT uses Stub
     3.
          Test verifies stub (passive)
     4.
                                              SUT
          OR stub asserts (active)

     Benefits:
                                             Stub
         Isolation
     

         Completeness
     

         Performance
     


18                                        Section: Testing Indirect Conditions
                             01/10/2009
Indirect Outputs




19               01/10/2009   Section: Testing Indirect Conditions
Indirect Outputs

         Types of output:
     




19                     01/10/2009   Section: Testing Indirect Conditions
Indirect Outputs

         Types of output:
     
             Log files written to
         –




19                          01/10/2009   Section: Testing Indirect Conditions
Indirect Outputs

         Types of output:
     
             Log files written to
         –
             Database tables altered
         –




19                        01/10/2009   Section: Testing Indirect Conditions
Indirect Outputs

         Types of output:
     
             Log files written to
         –
             Database tables altered
         –

             Emails sent
         –




19                        01/10/2009   Section: Testing Indirect Conditions
Indirect Outputs

         Types of output:
     
             Log files written to
         –
             Database tables altered
         –

             Emails sent
         –

         How can we verify these outputs?
     




19                        01/10/2009   Section: Testing Indirect Conditions
Indirect Outputs

         Types of output:
     
             Log files written to
         –
             Database tables altered
         –

             Emails sent
         –

         How can we verify these outputs?
     
             Check the real component
         –




19                        01/10/2009    Section: Testing Indirect Conditions
Indirect Outputs

         Types of output:
     
             Log files written to
         –
             Database tables altered
         –

             Emails sent
         –

         How can we verify these outputs?
     
             Check the real component
         –
             Replace with a mock object
         –




19                        01/10/2009      Section: Testing Indirect Conditions
What defines testable code?




20              01/10/2009   Section: Design for Testability
What defines testable code?

         Easier to test a new class or an existing one?
     
             Why? What makes a testable class?
         –

         Separation of concerns
     




20                       01/10/2009        Section: Design for Testability
What defines testable code?

         Easier to test a new class or an existing one?
     
             Why? What makes a testable class?
         –

         Separation of concerns
     
             High cohesion
         –




20                       01/10/2009        Section: Design for Testability
What defines testable code?

         Easier to test a new class or an existing one?
     
             Why? What makes a testable class?
         –

         Separation of concerns
     
             High cohesion
         –
             Low coupling
         –




20                       01/10/2009        Section: Design for Testability
What defines testable code?

         Easier to test a new class or an existing one?
     
             Why? What makes a testable class?
         –

         Separation of concerns
     
             High cohesion
         –
             Low coupling
         –

         When should we write tests?
     




20                       01/10/2009        Section: Design for Testability
What defines testable code?

         Easier to test a new class or an existing one?
     
             Why? What makes a testable class?
         –

         Separation of concerns
     
             High cohesion
         –
             Low coupling
         –

         When should we write tests?
     
             Test-first development
         –




20                         01/10/2009      Section: Design for Testability
Designing for Testability

          Architectural choices
      
              Layered design is more testable (i.e. MVC)
          –

          Design choices:
      
              What types to test?
          –
                   Concrete classes (good)
               
                   Abstract classes (better)
               

                   Interfaces (best)
               

              Avoid the singleton design pattern. Why?
          –

          Development process:
      
              Write the tests first
          –

21                              01/10/2009          Section: Design for Testability
Adding Tests to Old Code

          How do we safely fix/enhance untested code?
     


          Identify the area you need to change.
     1.
          Build a safety net there first
     2.
               Wrap existing code with unit tests before touching it
          –

          With safety net in place…
     3.
               Refactor the code to ease addition of new code
          1.
               Write unit test for issue
          2.
               Add code for fix/enhancement
          3.


22                           01/10/2009               Section: Testing Legacy Systems
Data-driven testing

          Parameterized testing
      
              Write single assert method that takes parameters
          –
              Runs the same test over and over with different inputs
          –

          MockRunner JDBC
      
              Mocks for Connection, Statement, ResultSet etc.
          –

          DBUnit and HSQLdb
      
              Loads data (XML files) into in-memory DB just for test
          –

          Others?
      



23                          01/10/2009              Section: Data-Driven Testing
Questions




24               01/10/2009

More Related Content

What's hot

Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
nickokiss
 

What's hot (20)

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
 
JUnit- A Unit Testing Framework
JUnit- A Unit Testing FrameworkJUnit- A Unit Testing Framework
JUnit- A Unit Testing Framework
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
GeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good TestsGeeCON 2012 Bad Tests, Good Tests
GeeCON 2012 Bad Tests, Good Tests
 
Confitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good TestsConfitura 2012 Bad Tests, Good Tests
Confitura 2012 Bad Tests, Good Tests
 
Junit 4.0
Junit 4.0Junit 4.0
Junit 4.0
 
Best practices unit testing
Best practices unit testing Best practices unit testing
Best practices unit testing
 
Unit testing best practices with JUnit
Unit testing best practices with JUnitUnit testing best practices with JUnit
Unit testing best practices with JUnit
 
Oh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationOh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to Mutation
 
Unit Testing in Java
Unit Testing in JavaUnit Testing in Java
Unit Testing in Java
 
Dev labs alliance top 20 testng interview questions for sdet
Dev labs alliance top 20 testng interview questions for sdetDev labs alliance top 20 testng interview questions for sdet
Dev labs alliance top 20 testng interview questions for sdet
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Thread & concurrancy
Thread & concurrancyThread & concurrancy
Thread & concurrancy
 
JUNit Presentation
JUNit PresentationJUNit Presentation
JUNit Presentation
 
The Best Pairwise Testing Tool / Best Orthogonal Array Tool Just Got Better
The Best Pairwise Testing Tool / Best Orthogonal Array Tool Just Got BetterThe Best Pairwise Testing Tool / Best Orthogonal Array Tool Just Got Better
The Best Pairwise Testing Tool / Best Orthogonal Array Tool Just Got Better
 
Junit
JunitJunit
Junit
 
Unit Test in Ruby on Rails by Minitest
Unit Test in Ruby on Rails by MinitestUnit Test in Ruby on Rails by Minitest
Unit Test in Ruby on Rails by Minitest
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
Simple Unit Testing With Netbeans 6.1
Simple Unit Testing With Netbeans 6.1Simple Unit Testing With Netbeans 6.1
Simple Unit Testing With Netbeans 6.1
 
Workshop unit test
Workshop   unit testWorkshop   unit test
Workshop unit test
 

Similar to Unit Testing in Java

Pivotal Labs Open View Presentation Quality Assurance And Developer Testing
Pivotal Labs Open View Presentation Quality Assurance And Developer TestingPivotal Labs Open View Presentation Quality Assurance And Developer Testing
Pivotal Labs Open View Presentation Quality Assurance And Developer Testing
guestc8adce
 
What's software testing
What's software testingWhat's software testing
What's software testing
Li-Wei Cheng
 
Testing artifacts test cases
Testing artifacts   test casesTesting artifacts   test cases
Testing artifacts test cases
Petro Chernii
 
[DSBW Spring 2009] Unit 09: Web Testing
[DSBW Spring 2009] Unit 09: Web Testing[DSBW Spring 2009] Unit 09: Web Testing
[DSBW Spring 2009] Unit 09: Web Testing
Carles Farré
 
Test Automation Principles
Test Automation PrinciplesTest Automation Principles
Test Automation Principles
NetSuite
 

Similar to Unit Testing in Java (20)

Pivotal Labs Open View Presentation Quality Assurance And Developer Testing
Pivotal Labs Open View Presentation Quality Assurance And Developer TestingPivotal Labs Open View Presentation Quality Assurance And Developer Testing
Pivotal Labs Open View Presentation Quality Assurance And Developer Testing
 
Just Java2007 - Daniel Wildt - Tools For Java Test Automation
Just Java2007 - Daniel Wildt - Tools For Java Test AutomationJust Java2007 - Daniel Wildt - Tools For Java Test Automation
Just Java2007 - Daniel Wildt - Tools For Java Test Automation
 
OSGi Applications Testing - André Elia Assad, System Engineer, Cesar
OSGi Applications Testing - André Elia Assad, System Engineer, CesarOSGi Applications Testing - André Elia Assad, System Engineer, Cesar
OSGi Applications Testing - André Elia Assad, System Engineer, Cesar
 
What's software testing
What's software testingWhat's software testing
What's software testing
 
Agile Java Testing With Open Source Frameworks
Agile Java Testing With Open Source FrameworksAgile Java Testing With Open Source Frameworks
Agile Java Testing With Open Source Frameworks
 
Groovy Testing Aug2009
Groovy Testing Aug2009Groovy Testing Aug2009
Groovy Testing Aug2009
 
Database Unit Testing Made Easy with VSTS
Database Unit Testing Made Easy with VSTSDatabase Unit Testing Made Easy with VSTS
Database Unit Testing Made Easy with VSTS
 
DevDay 2016: Dave Farley - Acceptance testing for continuous delivery
DevDay 2016: Dave Farley - Acceptance testing for continuous deliveryDevDay 2016: Dave Farley - Acceptance testing for continuous delivery
DevDay 2016: Dave Farley - Acceptance testing for continuous delivery
 
ICTSS 2010 - Iterative Software Testing Process for Scrum and Waterfall Projects
ICTSS 2010 - Iterative Software Testing Process for Scrum and Waterfall ProjectsICTSS 2010 - Iterative Software Testing Process for Scrum and Waterfall Projects
ICTSS 2010 - Iterative Software Testing Process for Scrum and Waterfall Projects
 
Test it! Unit, mocking and in-container Meet Arquillian!
Test it! Unit, mocking and in-container Meet Arquillian!Test it! Unit, mocking and in-container Meet Arquillian!
Test it! Unit, mocking and in-container Meet Arquillian!
 
Nunit
NunitNunit
Nunit
 
Testing artifacts test cases
Testing artifacts   test casesTesting artifacts   test cases
Testing artifacts test cases
 
Introduction to JUnit
Introduction to JUnitIntroduction to JUnit
Introduction to JUnit
 
Test Driven Development
Test Driven DevelopmentTest Driven Development
Test Driven Development
 
Groovy Testing Sep2009
Groovy Testing Sep2009Groovy Testing Sep2009
Groovy Testing Sep2009
 
Test Automation and Keyword-driven testing af Brian Nielsen, CISS/AAU
Test Automation and Keyword-driven testing af Brian Nielsen, CISS/AAUTest Automation and Keyword-driven testing af Brian Nielsen, CISS/AAU
Test Automation and Keyword-driven testing af Brian Nielsen, CISS/AAU
 
Lecture (Software Testing).pptx
Lecture (Software Testing).pptxLecture (Software Testing).pptx
Lecture (Software Testing).pptx
 
[DSBW Spring 2009] Unit 09: Web Testing
[DSBW Spring 2009] Unit 09: Web Testing[DSBW Spring 2009] Unit 09: Web Testing
[DSBW Spring 2009] Unit 09: Web Testing
 
Test
TestTest
Test
 
Test Automation Principles
Test Automation PrinciplesTest Automation Principles
Test Automation Principles
 

More from guy_davis

More from guy_davis (11)

Adopting Scrum and Agile
Adopting Scrum and AgileAdopting Scrum and Agile
Adopting Scrum and Agile
 
Pragmatic Programmer
Pragmatic ProgrammerPragmatic Programmer
Pragmatic Programmer
 
Content Caching with Rails
Content Caching with RailsContent Caching with Rails
Content Caching with Rails
 
Agile Software Development Methodologies
Agile Software Development MethodologiesAgile Software Development Methodologies
Agile Software Development Methodologies
 
Project Monitoring and Control
Project Monitoring and ControlProject Monitoring and Control
Project Monitoring and Control
 
The Human Side of Software Development
The Human Side of Software DevelopmentThe Human Side of Software Development
The Human Side of Software Development
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
 
Software Quality Plan
Software Quality PlanSoftware Quality Plan
Software Quality Plan
 
Unified Process
Unified ProcessUnified Process
Unified Process
 
Software Configuration Management
Software Configuration ManagementSoftware Configuration Management
Software Configuration Management
 
Quality Function Deployment
Quality Function DeploymentQuality Function Deployment
Quality Function Deployment
 

Recently uploaded

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
Safe Software
 
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
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 

Recently uploaded (20)

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
 
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
 
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
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
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
 
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
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
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
 
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
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
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...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
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...
 
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
 
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, ...
 
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
AI+A11Y 11MAY2024 HYDERBAD GAAD 2024 - HelloA11Y (11 May 2024)
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 

Unit Testing in Java

  • 1. Unit Testing in Java Testing for Developers Guy Davis 9/18/2006 01/10/2009
  • 2. Objectives Understand JUnit4 test framework  Learn unit testing methodology  What, when, and how to test… – Design app for testability and maintainability  Write maintainable unit tests  Assertions, Stubbing, Fixtures – Contrast with functional/acceptance testing  2 01/10/2009
  • 3. Contents Introduction to Unit Testing  Unit Testing Methodology  Test Style and Maintainability  JUnit Assertions  Test Fixture Setup  Testing Indirect Inputs and Outputs  Design for Testability  Testing Legacy Systems  Data-driven Testing  3 01/10/2009
  • 4. Why Test? Why Developer Testing?  Can’t QA “test quality into the product”? – Test terminology  Black-box and white-box tests – Unit, Component, System – Integration, Functional, Acceptance – Regression, Performance, Destructive – Question: Why automate tests?  4 01/10/2009 Section: Introduction to Unit Testing
  • 5. Compared to Functional Testing What is functional testing?  Tests the requirements, not the design. – Tests at the system level, not the unit (class). – Involves many interacting components  Typically requires more setup to test – Functional tests are more state-dependent  Automated functional tests avoid the GUI – Test the business processes and logic  5 01/10/2009 Section: Introduction to Unit Testing
  • 6. JUnit Test Framework Concepts in JUnit:  Test Method: single test – Test Case: group of test methods – Test Suite: group of test cases – Test Fixture: supporting objects – Recently updated to JUnit4  Uses assertions from JDK 1.5 – 6 Section: Introduction to Unit Testing 01/10/2009
  • 7. Running JUnit, Viewing Results Running JUnit in Eclipse  Run, Debug – Single/All – Running JUnit from Ant  Unit, Integration, All – Build system test results  Code coverage report  7 01/10/2009 Section: Introduction to Unit Testing
  • 8. Test Execution Steps in a test  Setup test fixtures: @BeforeClass, @Before – Exercise the system under test (SUT) – Verify the expected outcomes – Cleanup: @AfterClass, @After – Two possible outcomes:  Pass or Fail – 8 Section: Introduction to Unit Testing 01/10/2009
  • 9. Verifying Outcomes Use assertXYZ(“comment”, expected, actual)  Use most appropriate assert available – Add descriptive comment as first argument – Test exceptional outcomes  @Test(expected = IllegalArgumentException.class) – Use fail(“Should never …”) method – Performance assertions  @Test(timeout=500) – 9 Section: Introduction to Unit Testing 01/10/2009
  • 10. Finding Test Conditions What are the inputs to SUT?  Method arguments – System state – External data and files – What are the outputs of SUT?  Direct outputs: Returned values, exceptions – Side effects: state of system and its objects – 10 Section: Unit Testing Methodology 01/10/2009
  • 11. Finding Test Cases Boundary Values  For -256, -1, 0, 1, 255 for 8-bit integers – Cardinality Choices  0, 1, 2 – Null, “”, “Some String” – Failure cases  Nulls and other invalid inputs – 11 Section: Unit Testing Methodology 01/10/2009
  • 12. Test Granularity How many tests are needed?  Enough to cover all test conditions – If code coverage is 100%: Are you done? – How many conditions per test?  1:1 is ideal; easier to determine exact failure – Not so small it creates unnecessary overhead – 12 Section: Unit Testing Methodology 01/10/2009
  • 13. Assertions Goals for assertions:  Tests as documentation – Avoid test code duplication – Reduce likelihood of test errors; simplicity – Assertion patterns:  Expected Objects – Guard Assertions – Custom Asserts – 13 Section: JUnit Assertions 01/10/2009
  • 14. Terminology Clean Slate  Each test method does own setup – Independent and cohesive – Standard Test Fixture  Assumes standard environment for each – Shared Test Fixture  Standard environment shared by all tests – 14 Section: Test Fixture Setup 01/10/2009
  • 15. Practices Extract common fixtures into setUp()  Avoid code duplication for test setup – Write creation methods i.e. createPerson()  Place common cleanup into tearDown()  Better than many finally blocks in tests – Use inner classes (named & anonymous)  Avoids test code in production classes – Avoid hard-coded data in tests-> use constants  15 Section: Test Fixture Setup 01/10/2009
  • 16. What is a good test? Self-checking Unit testing Patterns   Single glance readable Repeatable –  Single condition test – Robust  Declarative style – Complete  Clean-slate setup – Efficient  Custom assertions – Stub out dependencies Specific –  Consistent naming – Reviewed  Back to front test coding – Test-driven development – 16 Section: Test Style and Maintainability 01/10/2009
  • 17. Indirect Inputs 17 Section: Testing Indirect Conditions 01/10/2009
  • 18. Indirect Inputs Types of inputs:  17 Section: Testing Indirect Conditions 01/10/2009
  • 19. Indirect Inputs Types of inputs:  Returned values internal to SUT – 17 Section: Testing Indirect Conditions 01/10/2009
  • 20. Indirect Inputs Types of inputs:  Returned values internal to SUT – Updateable parameters – 17 Section: Testing Indirect Conditions 01/10/2009
  • 21. Indirect Inputs Types of inputs:  Returned values internal to SUT – Updateable parameters – Internal exception handling – 17 Section: Testing Indirect Conditions 01/10/2009
  • 22. Indirect Inputs Types of inputs:  Returned values internal to SUT – Updateable parameters – Internal exception handling – How do we test this?  17 Section: Testing Indirect Conditions 01/10/2009
  • 23. Indirect Inputs Types of inputs:  Returned values internal to SUT – Updateable parameters – Internal exception handling – How do we test this?  Mock Objects (a.k.a. Stubs) – 17 Section: Testing Indirect Conditions 01/10/2009
  • 24. Stubbing Strategy Test creates stub 1. Stub provided to SUT Test 2. SUT uses Stub 3. Test verifies stub (passive) 4. SUT OR stub asserts (active) Benefits: Stub Isolation  Completeness  Performance  18 Section: Testing Indirect Conditions 01/10/2009
  • 25. Indirect Outputs 19 01/10/2009 Section: Testing Indirect Conditions
  • 26. Indirect Outputs Types of output:  19 01/10/2009 Section: Testing Indirect Conditions
  • 27. Indirect Outputs Types of output:  Log files written to – 19 01/10/2009 Section: Testing Indirect Conditions
  • 28. Indirect Outputs Types of output:  Log files written to – Database tables altered – 19 01/10/2009 Section: Testing Indirect Conditions
  • 29. Indirect Outputs Types of output:  Log files written to – Database tables altered – Emails sent – 19 01/10/2009 Section: Testing Indirect Conditions
  • 30. Indirect Outputs Types of output:  Log files written to – Database tables altered – Emails sent – How can we verify these outputs?  19 01/10/2009 Section: Testing Indirect Conditions
  • 31. Indirect Outputs Types of output:  Log files written to – Database tables altered – Emails sent – How can we verify these outputs?  Check the real component – 19 01/10/2009 Section: Testing Indirect Conditions
  • 32. Indirect Outputs Types of output:  Log files written to – Database tables altered – Emails sent – How can we verify these outputs?  Check the real component – Replace with a mock object – 19 01/10/2009 Section: Testing Indirect Conditions
  • 33. What defines testable code? 20 01/10/2009 Section: Design for Testability
  • 34. What defines testable code? Easier to test a new class or an existing one?  Why? What makes a testable class? – Separation of concerns  20 01/10/2009 Section: Design for Testability
  • 35. What defines testable code? Easier to test a new class or an existing one?  Why? What makes a testable class? – Separation of concerns  High cohesion – 20 01/10/2009 Section: Design for Testability
  • 36. What defines testable code? Easier to test a new class or an existing one?  Why? What makes a testable class? – Separation of concerns  High cohesion – Low coupling – 20 01/10/2009 Section: Design for Testability
  • 37. What defines testable code? Easier to test a new class or an existing one?  Why? What makes a testable class? – Separation of concerns  High cohesion – Low coupling – When should we write tests?  20 01/10/2009 Section: Design for Testability
  • 38. What defines testable code? Easier to test a new class or an existing one?  Why? What makes a testable class? – Separation of concerns  High cohesion – Low coupling – When should we write tests?  Test-first development – 20 01/10/2009 Section: Design for Testability
  • 39. Designing for Testability Architectural choices  Layered design is more testable (i.e. MVC) – Design choices:  What types to test? – Concrete classes (good)  Abstract classes (better)  Interfaces (best)  Avoid the singleton design pattern. Why? – Development process:  Write the tests first – 21 01/10/2009 Section: Design for Testability
  • 40. Adding Tests to Old Code How do we safely fix/enhance untested code?  Identify the area you need to change. 1. Build a safety net there first 2. Wrap existing code with unit tests before touching it – With safety net in place… 3. Refactor the code to ease addition of new code 1. Write unit test for issue 2. Add code for fix/enhancement 3. 22 01/10/2009 Section: Testing Legacy Systems
  • 41. Data-driven testing Parameterized testing  Write single assert method that takes parameters – Runs the same test over and over with different inputs – MockRunner JDBC  Mocks for Connection, Statement, ResultSet etc. – DBUnit and HSQLdb  Loads data (XML files) into in-memory DB just for test – Others?  23 01/10/2009 Section: Data-Driven Testing
  • 42. Questions 24 01/10/2009

Editor's Notes

  1. Automate tests: Cost not proportional to number of test runs like manual is More repeatable and less error-prone More fun and more likely to happen Goal of testing is to prevent defects, not find as many as possible. Root-cause analysis, fix the source of the problem.
  2. Mention how I always mix up the TestCase with a test case which is a certain scenario.
  3. Show the test results links for branches. Show Cobertura report.
  4. Show LoadModel test case Question: What happened to Error outcome from JUnit?
  5. Can either make static Assert.assertFoo() calls or use a static import to shorten this down. Show example of exception assertion in DVAdapterTest class.
  6. Expected objects: don’t compare pointX and pointY variables, just compare Point (object) Guard assertion: assertNotNull(collection) before asserting about its contents Custom assert: assertExactlyOneChildNode(node); created during test refactoring
  7. Clean Slate: watch out for code duplication Standard: brittleness from dependence on external data Shared: test run wars, interactions between tests, unrepeatable tests, example is our DV_TEST database
  8. A mock object fills the role of the real dependency by acting just like it.
  9. A mock object fills the role of the real dependency by acting just like it.
  10. A mock object fills the role of the real dependency by acting just like it.
  11. A mock object fills the role of the real dependency by acting just like it.
  12. A mock object fills the role of the real dependency by acting just like it.
  13. A mock object fills the role of the real dependency by acting just like it.
  14. Install Stub into SUT by: Passing as argument Passing as constructor argument Set explicitly with setter method Set in the environment (preferences, system property, JNDI) Discuss Active versus Passive stubs (Active stubs participate in the verification)
  15. Real component: Talk about DBUnit and embedded databases like HSQL for Merge tests. Mock object: Show MockRunner objects in LoadModel test for working JDBC. Mention that mock objects don’t need to be created by hand. Projects like EasyMock, jMock, and MockMaker can auto-generate.
  16. Real component: Talk about DBUnit and embedded databases like HSQL for Merge tests. Mock object: Show MockRunner objects in LoadModel test for working JDBC. Mention that mock objects don’t need to be created by hand. Projects like EasyMock, jMock, and MockMaker can auto-generate.
  17. Real component: Talk about DBUnit and embedded databases like HSQL for Merge tests. Mock object: Show MockRunner objects in LoadModel test for working JDBC. Mention that mock objects don’t need to be created by hand. Projects like EasyMock, jMock, and MockMaker can auto-generate.
  18. Real component: Talk about DBUnit and embedded databases like HSQL for Merge tests. Mock object: Show MockRunner objects in LoadModel test for working JDBC. Mention that mock objects don’t need to be created by hand. Projects like EasyMock, jMock, and MockMaker can auto-generate.
  19. Real component: Talk about DBUnit and embedded databases like HSQL for Merge tests. Mock object: Show MockRunner objects in LoadModel test for working JDBC. Mention that mock objects don’t need to be created by hand. Projects like EasyMock, jMock, and MockMaker can auto-generate.
  20. Real component: Talk about DBUnit and embedded databases like HSQL for Merge tests. Mock object: Show MockRunner objects in LoadModel test for working JDBC. Mention that mock objects don’t need to be created by hand. Projects like EasyMock, jMock, and MockMaker can auto-generate.
  21. Real component: Talk about DBUnit and embedded databases like HSQL for Merge tests. Mock object: Show MockRunner objects in LoadModel test for working JDBC. Mention that mock objects don’t need to be created by hand. Projects like EasyMock, jMock, and MockMaker can auto-generate.
  22. Talk about how much setup some tests require. Then show the answer: separation of concerns Then ask when should we test?
  23. Talk about how much setup some tests require. Then show the answer: separation of concerns Then ask when should we test?
  24. Talk about how much setup some tests require. Then show the answer: separation of concerns Then ask when should we test?
  25. Talk about how much setup some tests require. Then show the answer: separation of concerns Then ask when should we test?
  26. Talk about how much setup some tests require. Then show the answer: separation of concerns Then ask when should we test?
  27. Talk about how much setup some tests require. Then show the answer: separation of concerns Then ask when should we test?
  28. Talk about how much setup some tests require. Then show the answer: separation of concerns Then ask when should we test?
  29. See section 11 page 7 last slide for reasons.
  30. Mention that this can be hard as the original code wasn’t written with testability in mind. Likely it is highly coupled and not cohesive. Normally, you will need to iterate around the “write tests & refactor” loop until you have decent coverage.
  31. Show LoadModelTest for the Mockrunner example. Show AbstractPreferencesTestCase for the DBUnit.