GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Python Technologies
  • Databases
  • Computer Programming
  • Web Development
  • Java Technologies
  • Computer Science
  • Mobile Development
  • Big Data & Analytics
  • Microsoft Technologies
  • DevOps
  • Latest Technologies
  • Machine Learning
  • Digital Marketing
  • Software Quality

This view

  • Original page
  • New address

GeezerVison is showing www.tutorialspoint.com — Python - Mocking and Stubbing

Python Tutorial
  • Python - Home
  • Python - Overview
  • Python - History
  • Python - Features
  • Python vs C++
  • Python - Hello World Program
  • Python - Application Areas
  • Python - Interpreter
  • Python - Environment Setup
  • Python - Virtual Environment
  • Python - Basic Syntax
  • Python - Variables
  • Python - Private Variables
  • Python - Data Types
  • Python - Type Casting
  • Python - Unicode System
  • Python - Literals
  • Python - Operators
  • Python - Arithmetic Operators
  • Python - Comparison Operators
  • Python - Assignment Operators
  • Python - Logical Operators
  • Python - Bitwise Operators
  • Python - Membership Operators
  • Python - Identity Operators
  • Python - Walrus Operator
  • Python - Operator Precedence
  • Python - Comments
  • Python - User Input
  • Python - Numbers
  • Python - Booleans
  • Python - Floating Points
  • Python - Control Flow
  • Python - Decision Making
  • Python - If Statement
  • Python - If else
  • Python - Nested If
  • Python - Conditional User Inputs
  • Python - Match-Case Statement
  • Python - Loops
  • Python - for Loops
  • Python - for-else Loops
  • Python - While Loops
  • Python - break Statement
  • Python - continue Statement
  • Python - pass Statement
  • Python - Nested Loops
  • Python Functions & Modules
  • Python - Functions
  • Python - Default Arguments
  • Python - Keyword Arguments
  • Python - Keyword-Only Arguments
  • Python - Positional Arguments
  • Python - Positional-Only Arguments
  • Python - Arbitrary Arguments
  • Python - Variables Scope
  • Python - Function Annotations
  • Python - Modules
  • Python - Packing and Unpacking
  • Python - Built in Functions
  • Python Strings
  • Python - Strings
  • Python - Slicing Strings
  • Python - Modify Strings
  • Python - String Concatenation
  • Python - String Formatting
  • Python - Escape Characters
  • Python - String Methods
  • Python - String Exercises
  • Python Lists
  • Python - Lists
  • Python - Access List Items
  • Python - Change List Items
  • Python - Add List Items
  • Python - Remove List Items
  • Python - Loop Lists
  • Python - List Comprehension
  • Python - Sort Lists
  • Python - Copy Lists
  • Python - Join Lists
  • Python - List Methods
  • Python - List Exercises
  • Python Tuples
  • Python - Tuples
  • Python - Access Tuple Items
  • Python - Update Tuples
  • Python - Unpack Tuples
  • Python - Loop Tuples
  • Python - Join Tuples
  • Python - Tuple Methods
  • Python - Namedtuple
  • Python - Tuple Exercises
  • Python Sets
  • Python - Sets
  • Python - Access Set Items
  • Python - Add Set Items
  • Python - Remove Set Items
  • Python - Loop Sets
  • Python - Join Sets
  • Python - Copy Sets
  • Python - Set Operators
  • Python - Set Methods
  • Python - Set Exercises
  • Python Dictionaries
  • Python - Dictionaries
  • Python - Access Dictionary Items
  • Python - Change Dictionary Items
  • Python - Add Dictionary Items
  • Python - Remove Dictionary Items
  • Python - Dictionary View Objects
  • Python - Loop Dictionaries
  • Python - Copy Dictionaries
  • Python - Nested Dictionaries
  • Python - Dictionary Methods
  • Python - Dictionary Exercises
  • Python Arrays
  • Python - Arrays
  • Python - Access Array Items
  • Python - Add Array Items
  • Python - Remove Array Items
  • Python - Loop Arrays
  • Python - Copy Arrays
  • Python - Reverse Arrays
  • Python - Sort Arrays
  • Python - Join Arrays
  • Python - Array Methods
  • Python - Array Exercises
  • Python File Handling
  • Python - File Handling
  • Python - Write to File
  • Python - Read Files
  • Python - Renaming and Deleting Files
  • Python - Directories
  • Python - File Methods
  • Python - OS File/Directory Methods
  • Python - OS Path Methods
  • Object Oriented Programming
  • Python - OOPs Concepts
  • Python - Classes & Objects
  • Python - Class Attributes
  • Python - Class Methods
  • Python - Static Methods
  • Python - Constructors
  • Python - Access Modifiers
  • Python - Inheritance
  • Python - Multiple Inheritance
  • Python - Multilevel Inheritance
  • Python - Polymorphism
  • Python - Method Overriding
  • Python - Method Overloading
  • Python - Dynamic Binding
  • Python - Dynamic Typing
  • Python - Abstraction
  • Python - Encapsulation
  • Python - Interfaces
  • Python - Packages
  • Python - Inner Classes
  • Python - Anonymous Class and Objects
  • Python - Singleton Class
  • Python - Wrapper Classes
  • Python - Enums
  • Python - Reflection
  • Python - Data Classes
  • Python Errors & Exceptions
  • Python - Syntax Errors
  • Python - Exceptions
  • Python - try-except Block
  • Python - try-finally Block
  • Python - Raising Exceptions
  • Python - Exception Chaining
  • Python - Nested try Block
  • Python - User-defined Exception
  • Python - Logging
  • Python - Assertions
  • Python - Warnings
  • Python - Built-in Exceptions
  • Python - Debugger (PDB)
  • Python Multithreading
  • Python - Multithreading
  • Python - Thread Life Cycle
  • Python - Creating a Thread
  • Python - Starting a Thread
  • Python - Joining Threads
  • Python - Naming Thread
  • Python - Thread Scheduling
  • Python - Thread Pools
  • Python - Main Thread
  • Python - Thread Priority
  • Python - Daemon Threads
  • Python - Synchronizing Threads
  • Python Synchronization
  • Python - Inter-thread Communication
  • Python - Thread Deadlock
  • Python - Interrupting a Thread
  • Python Networking
  • Python - Networking
  • Python - Socket Programming
  • Python - URL Processing
  • Python - Generics
  • Python Libraries
  • NumPy Tutorial
  • Pandas Tutorial
  • SciPy Tutorial
  • Matplotlib Tutorial
  • Django Tutorial
  • OpenCV Tutorial
  • Python Miscellenous
  • Python - Date & Time
  • Python - Maths
  • Python - Iterators
  • Python - Generators
  • Python - Generator Expressions
  • Python - Lambda Expressions
  • Python - Closures
  • Python - Decorators
  • Python - Recursion
  • Python - Reg Expressions
  • Python - PIP
  • Python - Database Access
  • Python - Weak References
  • Python - Serialization
  • Python - Templating
  • Python - Output Formatting
  • Python - Performance Measurement
  • Python - Data Compression
  • Python - CGI Programming
  • Python - XML Processing
  • Python - GUI Programming
  • Python - Command-Line Arguments
  • Python - Docstrings
  • Python - JSON
  • Python - Sending Email
  • Python - Further Extensions
  • Python - Tools/Utilities
  • Python - Odds and Ends
  • Python - GUIs
  • Python Advanced Concepts
  • Python - Abstract Base Classes
  • Python - Custom Exceptions
  • Python - Higher Order Functions
  • Python - Object Internals
  • Python - Memory Management
  • Python - Metaclasses
  • Python - Metaprogramming with Metaclasses
  • Python - Mocking and Stubbing
  • Python - Monkey Patching
  • Python - Signal Handling
  • Python - Type Hints
  • Python - Automation Tutorial
  • Python - Humanize Package
  • Python - Context Managers
  • Python - Coroutines
  • Python - Descriptors
  • Python - Diagnosing and Fixing Memory Leaks
  • Python - Immutable Data Structures
  • Python - Domain Specific Language (DSL)
  • Python - Data Model
  • Python Useful Resources
  • Python - Questions & Answers
  • Python - Interview Questions & Answers
  • Python - Online Quiz
  • Python - Quick Guide
  • Python - Reference
  • Python - Cheatsheet
  • Python - Projects
  • Python - Useful Resources
  • Python - Discussion
  • Python Compiler
  • NumPy Compiler
  • Matplotlib Compiler
  • SciPy Compiler
Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Online Resume Builder
  • HR Interview Questions
  • Computer Glossary
  • Who is Who

Python - Mocking and Stubbing



Previous
Quiz
Next

Python mocking and stubbing are important techniques in unit testing that help to isolate the functionality being tested by replacing real objects or methods with controlled substitutes. In this chapter we are going to understand about Mocking and Stubbing in detail −

Python Mocking

Mocking is a testing technique in which mock objects are created to simulate the behavior of real objects.

This is useful when testing a piece of code that interacts with complex, unpredictable or slow components such as databases, web services or hardware devices.

The primary purpose of mocking is to isolate the code under test and ensure that its behavior is evaluated independently of its dependencies.

Key Characteristics of Mocking

The following are the key characteristics of mocking in python −

  • Behavior Simulation: Mock objects can be programmed to return specific values, raise exceptions or mimic the behavior of real objects under various conditions.
  • Interaction Verification: Mocks can record how they were used by allowing the tester to verify that specific methods were called with the expected arguments.
  • Test Isolation:By replacing real objects with mocks, tests can focus on the logic of the code under test without worrying about the complexities or availability of external dependencies.

Example of Python Mocking

Following is the example of the database.get_user method, which is mocked to return a predefined user dictionary. The test can then verify that the method was called with the correct arguments −

from unittest.mock import Mock

# Create a mock object
database = Mock()

# Simulate a method call
database.get_user.return_value = {"name": "Prasad", "age": 30}

# Use the mock object
user = database.get_user("prasad_id")
print(user)  

# Verify the interaction
database.get_user.assert_called_with("prasad_id") 

Output

{'name': 'Prasad', 'age': 30}

Python Stubbing

Stubbing is a related testing technique where certain methods or functions are replaced with "stubs" that return fixed, predetermined responses.

Stubbing is simpler than mocking because it typically does not involve recording or verifying interactions. Instead, stubbing focuses on providing controlled inputs to the code under test by ensuring consistent and repeatable results.

Key Characteristics of Stubbing

The following are the key characteristics of Stubbing in python −

  • Fixed Responses: Stubs return specific, predefined values or responses regardless of how they are called.
  • Simplified Dependencies: By replacing complex methods with stubs, tests can avoid the need to set up or manage intricate dependencies.
  • Focus on Inputs: Stubbing emphasizes providing known inputs to the code under test by allowing the tester to focus on the logic and output of the tested code.

Example of Python Stubbing

Following is the example of the get_user_from_db function, which is stubbed to always return a predefined user dictionary. The test does not need to interact with a real database for simplifying the setup and ensuring consistent results −

from unittest.mock import patch

# Define the function to be stubbed
def get_user_from_db(user_id):
   # Simulate a complex database operation
   pass

# Test the function with a stub
with patch('__main__.get_user_from_db', return_value={"name": "Prasad", "age": 25}):
   user = get_user_from_db("prasad_id")
   print(user)  

Output

{'name': 'Prasad', 'age': 25}

Python Mocking Vs. Stubbing

The comparison of the Mocking and Stubbing key features, purposes and use cases gives the clarity on when to use each method. By exploring these distinctions, developers can create more effective and maintainable tests which ultimately leads to higher quality software.

The following table shows the key difference between mocking and stubbing based on the different criteria −

Criteria Mocking Stubbing
Purpose Simulate the behavior of real objects Provide fixed, predetermined responses
Interaction Verification Can verify method calls and arguments Typically does not verify interactions
Complexity More complex; can simulate various behaviors Simpler; focuses on providing controlled inputs
Use Case Isolate and test code with complex dependencies Simplify tests by providing known responses
Recording Behavior Records how methods were called Does not record interactions
State Management Can maintain state across calls Usually stateless; returns fixed output
Framework Support Primarily uses unittest.mock with features like Mock and MagicMock Uses unittest.mock's patch for simple replacements
Flexibility Highly flexible; can simulate exceptions and side effects Limited flexibility; focused on return values
Tutorix - AI Tutor
Previous Quiz Next
Advertisements
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.