Fl4m3Ph03n1x
Completely replace a dependency with a mock
Background
I have an app called :my_app that has a dependency called :my_dep. :my_dep connects to the internet and downloads a bunch of files. Every time I run :my_app, it executes :my_dep because :my_dep is a runtime dependency. So, when I run tests, launch the app in my DEV environment or simply run it, :my_dep always connects to the internet to download files.
If :my_dep cannot connect, it fails, and because it is a runtime dependency, :my_app fails to launch.
My Approach
The current system means I can’t run local tests nor do anything without a connection to the internet. So my attempt at fixing this was to follow the approach suggested by mocks and explicit contracts and to create an interface (add a boundary between :my_app and :my_dep) and to create a mock that implements the interface.
Following is an example of how I am implementing this technique:
Geolocation Module of MyApp:
defmodule MyApp.Geolocation do
@geo Application.get_env(:my_app, :my_dep_api)
require Logger
@spec geolocate(String.t) :: String.t
def geolocate(ip) do
ip
|> @geo.find()
|> get_country(ip)
end
@spec get_country({:ok, [String.t]}, String.t) :: String.t
defp get_country({:ok, [country | _tail]}, _ip), do: String.upcase(country)
end
DEV config file of MyApp:
config :my_app,
my_dep_api: MyDep.StaticMock
The StaticMock file:
defmodule MyDep.StaticMock do
@behaviour MyApp.IMyDep
@behaviour MyApp.IMyDep
@spec find(String.t) :: {:ok, [String.t]}
def find(_ip), do: {:ok, ["ES", "cat", "b"]}
end
Problem
The issue here, is that when I launch my app in DEV, it still runs the original my_dep app and it still tries to connect and download the files.
Question
How can I fix this?
Marked As Solved
al2o3cr
Apologies for the confusion, I totally skipped this part of your question:
The right place to fix this isn’t in MyApp.Geolocation, but rather where :my_dep is being started: might be in :my_app’s application.exs or in mix.exs.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #javascript
- #code-sync
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance








