Sobes.tech
Junior — Middle

What principles should be used when writing functions to ensure their easy testing with unit tests?

sobes.tech AI

Answer from AI

To ensure functions are easily testable with unit tests, it is recommended to follow these principles:

  • Single responsibility — a function should perform one specific task.
  • Minimal external dependencies — avoid accessing global variables, databases, or files within the function.
  • Explicit input and output — all necessary data should be passed via parameters, and the result returned explicitly.
  • No side effects — the function should not change state outside its scope.
  • Use default parameters and dependency injection — to facilitate dependency substitution in tests.

Example of a simple, easily testable function:

def add(a, b):
    return a + b

Such a function is easy to cover with tests because it does not depend on external state.

If the function interacts with external resources, it is better to isolate the logic into separate pure functions and use mock objects in tests.