Isolating Code

Testing Elixir — by Andrea Leopardi, Jeffrey Matthias (18 / 80)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Refactoring Toward Pure Functions | TOC | Wrapping Up 👉

We can employ multiple strategies to test our code in a way that removes outside variables, controlling the situation in which our code under test must perform and allowing us to expect a specific outcome. We’ll cover the easiest method — injecting dependencies and creating basic substitutes (test doubles) — in order to add another option to your testing tool belt.

Dependency Injection

Before we can leverage dependency injection to isolate the behavior of our code under test, let’s take a moment to define dependency injection. A dependency is any code that your code relies on. 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 name of the dependency, 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 and through the application environment. Utilizing DI in our tests allows us to create replacement dependencies that behave in predictable ways, allowing the tests to focus on the logic inside the code under test.

Passing a dependency as a parameter is the more common way to inject dependencies in unit testing, which is the style that we’ll focus on first. In later chapters, we’ll cover dependency injection via the…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.