Finer Control over Dependency Injection

Learn how Dependency Injection can be fine-tuned.

An alternative to injecting a whole function is to pass in a single value. An example we might see in code is when the outside dependency is the system time. If our code under test needs to do something with system time, it’s very difficult for our tests to assert a known response or value unless we can control system time. While controlling our code’s concept of system time is easy in some languages, it isn’t in Elixir. That makes this scenario a perfect candidate for injecting a single value.

The following code allows for an injected value, but it defaults to the result of a function call if no parameter is passed:

Get hands-on with 1400+ tech skills courses.