Talks - Liz Acosta: Mock It Till You Make It: How to Verify Your External Mocks Without Ever...

Learn best practices for mocking in Python tests: when to use mocks, how to keep them accurate, and techniques to verify they match production behavior.

Key takeaways
  • Unit tests should be descriptive, automatic, independent, repeatable and deterministic with precise assertions

  • Mocking is essential for modern software testing to isolate components and control dependencies, but should be used judiciously:

    • Only mock what you need
    • Keep mocks simple
    • Occasionally verify mocks for accuracy
    • Don’t mock what you don’t own
  • Use auto_spec=True when mocking to ensure mocks stay true to the original object’s methods and attributes

  • The @patch decorator helps target and replace specific objects with mocks during testing

  • Skip tests can be used to separate tests into different environments (dev vs prod) and control when tests run

  • Complex mocking (mocks within mocks) is often a code smell indicating need to refactor

  • Unit tests serve as documentation - they help new developers understand code functionality

  • Mocks can fall out of sync with reality and make tests meaningless if not maintained properly

  • Test failures should help identify actual issues rather than mock configuration problems

  • Writing tests makes us better engineers by forcing us to consider expected behaviors and proper system design