I am looking for readable (self-explained) python examples for Inverse Of Control (IOC) & Dependency Injection (DI).
Thanks in advance,
DI is really quite a simple idea: just pass in the things that a class (or function) needs to do its job, rather than creating them in there. It’s useful because it lets you substitute the real things with others to make testing easier.
I wrote a tutorial on how to use DI to control date and time in tests: Controlling date and time in tests.
Nice tutorial. I’ll just add that with Python default args, the injection can be optional and only used when testing (until the app needs variable callables). Example:
def func(item, todayfunc=datetime.today): today = todayfunc() ...
For testing, inject the callable:
def date220517(): return date(year=2022, month=9, day=17) ... def test_func(self): ... self.assertEqual(func(item, date220517), 2)