Isolating Code

Learn about the fundamentals of dependency injection in your code.

There are plenty of times when we can’t draw clear lines about what can be extracted into a new function. When that’s the case, we still have another tool at our disposal to create a controlled environment to exercise our code. We can create a replacement for the dependency, isolating our code.

Dependency Injection

Dependency injection (often abbreviated as DI) is a fancy name for any system that allows your code to utilize a dependency without hard-coding the dependency’s name, allowing any unit of code that meets a contract to be used.

In Elixir, we have two common ways to inject a dependency:

  • As a parameter to a function
  • Through the application environment

Utilizing DI in our tests allows us to create replacement dependencies that behave in predictable ways, focusing on the logic inside the code under test.

Get hands-on with 1200+ tech skills courses.