Finer Control over Dependency Injection
Explore how to gain finer control over dependency injection in Elixir unit tests by passing single values like system time. Learn to isolate code under test, use boundary testing with DateTime values, and create helper functions to improve test readability and control.
We'll cover the following...
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:
In the above code, in line 8, we can see that without a value passed in, the result of DateTime.utc_now/0 will be bound to the variable datetime. Our tests will pass a value, overriding the default, but the code will use the ...