Mastering Unit Testing Using Mockito and JUnit

Book description

An advanced guide to mastering unit testing using Mockito and JUnit

In Detail

It is insanity to keep doing things the same way and expect them to improve. Any program is useful only when it is functional; hence, before applying complex tools, patterns, or APIs to your production code, checking software functionality is must. Automated JUnit tests help you verify your assumptions continuously, detect side effects quickly, and also help you save time.

This book will provide the skills you need to successfully build and maintain meaningful JUnit test cases. You will begin with how to use advanced JUnit 4 features, improve code coverage, automate JUnit tests, monitor code quality, write JUnit tests for the database and web tier refactor legacy code, mock external dependencies using Mockito, and write testable code using test-driven development. By sequentially working through the steps in each chapter, you will quickly master the advanced JUnit features.

What You Will Learn

  • Write advanced JUnit test cases using advanced JUnit 4 features
  • Automate JUnit test cases using Gradle, Maven, and Ant scripting
  • Practice continuous integration with Jenkins and Ant, Maven, and Gradle scripting
  • Monitor code quality with the SonarQube dashboard
  • Analyze static code using PMD, Checkstyle, and FindBugs
  • Master code coverage with Clover, Cobertura, EclEmma, and JaCoCo
  • Design for testability and refactor legacy code
  • Practice test-driven development with Mockito

Table of contents

  1. Mastering Unit Testing Using Mockito and JUnit
    1. Table of Contents
    2. Mastering Unit Testing Using Mockito and JUnit
    3. Credits
    4. About the Author
    5. About the Reviewers
    6. www.PacktPub.com
      1. Support files, eBooks, discount offers, and more
        1. Why subscribe?
        2. Free access for Packt account holders
    7. Preface
      1. What this book covers
      2. What you need for this book
      3. Who this book is for
      4. Conventions
      5. Reader feedback
      6. Customer support
        1. Downloading the example code
        2. Errata
        3. Piracy
        4. Questions
    8. 1. JUnit 4 – a Total Recall
      1. Defining unit testing
      2. Working with JUnit 4
        1. Setting up Eclipse
        2. Running the first unit test
          1. Exploring annotations
          2. Verifying test conditions with Assertion
        3. Working with exception handling
        4. Exploring the @RunWith annotation
      3. Working with JUnit 4++
        1. Ignoring a test
        2. Executing tests in order
        3. Learning assumptions
        4. Exploring the test suite
        5. Asserting with assertThat
          1. Comparing matchers – equalTo, is, and not
          2. Working with compound value matchers – either, both, anyOf, allOf, and not
          3. Working with collection matchers – hasItem and hasItems
          4. Exploring string matchers – startsWith, endsWith, and containsString
          5. Exploring built-in matchers
          6. Building a custom matcher
        6. Creating parameterized tests
          1. Working with parameterized constructors
          2. Working with parameterized methods
          3. Giving a name
        7. Working with timeouts
        8. Exploring JUnit theories
          1. Externalizing data using @ParametersSuppliedBy and ParameterSupplier
        9. Dealing with JUnit rules
          1. Playing with the timeout rule
          2. Working with the ExpectedException rule
          3. Unfolding the TemporaryFolder rule
          4. Exploring the ErrorCollector rule
          5. Working with the Verifier rule
          6. Learning the TestWatcher rule
          7. Working with the TestName rule
          8. Handling external resources
        10. Exploring JUnit categories
      4. Summary
    9. 2. Automating JUnit Tests
      1. Continuous Integration
        1. Benefits of CI
        2. Gradle automation
          1. Getting started
          2. Gradling
            1. Ordering subtasks using doFirst and doLast
            2. Default tasks
            3. The task dependency
            4. Daemon
          3. Gradle plugins
            1. The Eclipse plugin
            2. The Java plugin
        3. Maven project management
          1. Installation
          2. The Archetype plugin
          3. The Project Object Model (POM) file
          4. Project dependency
          5. The build life cycle
            1. Compiling the project
            2. Testing the project
              1. Packaging the project
          6. The clean life cycle
          7. The site life cycle
        4. Another neat tool (Ant)
      2. Jenkins
        1. The Gradle project
        2. The Maven project
        3. Building the Ant project
      3. Summary
    10. 3. Test Doubles
      1. Dummy
      2. Stub
      3. Fake
      4. Mock
      5. Spy
      6. Summary
    11. 4. Progressive Mockito
      1. Working with Mockito
        1. Why should you use Mockito?
        2. Qualities of unit testing
      2. Drinking Mockito
        1. Configuring Mockito
        2. Mocking in action
          1. Mocking objects
          2. Stubbing methods
          3. Verifying the method invocation
            1. Why do we use verify?
            2. Verifying in depth
            3. Verifying zero and no more interactions
          4. Using argument matcher
            1. Why do we need wildcard matchers?
            2. The ArgumentMatcher class
          5. Throwing exceptions
          6. Stubbing consecutive calls
          7. Stubbing with an Answer
          8. Spying objects
          9. Stubbing void methods
          10. Capturing arguments with ArgumentCaptor
          11. Verifying the invocation order
          12. Changing the default settings
          13. Resetting mock objects
          14. Exploring Mockito annotations
          15. Working with inline stubbing
          16. Determining mocking details
        3. Behavior-driven development with Mockito
          1. Writing tests in BDD style
          2. The BDD syntax
      3. Summary
    12. 5. Exploring Code Coverage
      1. Understanding code coverage
        1. Learning the inner details of code instrumentation
      2. Configuring the Eclipse plugin
        1. Uncovering the Clover plugin
        2. Working with the EclEmma plugin
        3. Examining the eCobertura plugin
      3. Measuring coverage using Gradle
      4. Working with the Maven Cobertura plugin
      5. Running the Cobertura Ant task
      6. Summary
    13. 6. Revealing Code Quality
      1. Understanding the static code analysis
      2. Working with the Checkstyle plugin
      3. Exploring the FindBugs plugin
      4. Working with the PMD plugin
      5. Monitoring code quality with SonarQube
        1. Running SonarQube
        2. Analyzing code with the SonarQube runner
        3. Improving quality with the Sonar Eclipse plugin
        4. Monitoring quality with Gradle and SonarQube
        5. Monitoring quality with Maven and SonarQube
        6. Monitoring quality with Ant and SonarQube
      6. Getting familiar with false positives
      7. Summary
    14. 7. Unit Testing the Web Tier
      1. Unit testing servlets
        1. Building and unit testing a J2EE web application
      2. Playing with Spring MVC
      3. Summary
    15. 8. Playing with Data
      1. Separating concerns
      2. Unit testing the persistence logic
      3. Simplifying persistence with Spring
      4. Verifying the system integrity
      5. Writing integration tests with Spring
      6. Summary
    16. 9. Solving Test Puzzles
      1. Working with the legacy code
        1. Working with testing impediments
      2. Designing for testability
        1. Identifying constructor issues
        2. Realizing initialization issues
        3. Working with private methods
        4. Working with final methods
        5. Exploring static method issues
        6. Working with final classes
        7. Learning the new attribute
        8. Exploring static variables and blocks
      3. Working with greenfield code
      4. Summary
    17. 10. Best Practices
      1. Writing meaningful tests
        1. Improving readability
        2. Breaking everything that could possibly break
        3. Ignoring simple test cases
        4. Verifying invalid parameters
        5. Relying on direct testing
        6. Staying away from debugging
        7. Avoiding generic matchers
        8. Keeping away from @ignore
        9. Eluding debug messages
      2. Automating JUnit tests
      3. Configuring tests
        1. Running in-memory tests
        2. Staying away from Thread.sleep
        3. Keeping unit tests away from the production code
        4. Avoiding static variables
        5. Assuming the test execution order
        6. Loading data from files
        7. Invoking super.setUp() and super.tearDown()
        8. Staying away from side effects
        9. Working with locales
        10. Working with dates
      4. Working with assertions
        1. Using the correct assertion
        2. Maintaining the assertEquals parameter order
        3. Striving for one assertion per test
      5. Handling exceptions
      6. Working with test smells
        1. Refactoring duplicates
        2. Refactoring the test control logic
        3. Removing the test logic from the production code
        4. Refactoring over engineered tests
      7. Summary
    18. Index

Product information

  • Title: Mastering Unit Testing Using Mockito and JUnit
  • Author(s): Sujoy Acharya
  • Release date: July 2014
  • Publisher(s): Packt Publishing
  • ISBN: 9781783982509