monkeypatch
Replacing a name inside a module while a test runs, such as swapping a clock function, and restoring it afterwards.
In more detail
pytest's monkeypatch fixture and unittest.mock.patch both do this. Patch the name where your module looks it up, not where the library defines it, or the real object keeps running. Prefer passing the dependency in when the design allows.
Related terms
- dependency injection — Giving an object the collaborators it needs from outside, usually through its constructor, instead of letting it create or look them up itself.
- seam — A place in the code where you can swap in different behaviour without editing the code itself, such as a parameter.
- unittest.mock — The mocking library in Python's standard library, which builds mock objects and records how they were called.
Taught in
- What Test Doubles Are For — Automated Testing, TDD & Quality Engineering
- Testing Time And Randomness — Automated Testing, TDD & Quality Engineering