Dependency Injection

Whats a good strategy here? I have created a module that makes external API calls but I want to mock these in my tests and other times (like with special header parameters so I can integration test) I’m ok with just manually creating the mock modules but whats a good way to switch between the two?

3 Likes

I believe the using macro and metaprogramming may be what you’re looking
for. I suggest taking a look at Ecto and how it uses macros for using its
adapters.

2 Likes

Hi @ctrlshiftbryan,

You may find this blog posting from @josevalim worthwhile reading.


Onorio

6 Likes

I like to pass in function maps to my program. Basically I just create a map with function captures as values and it’s as simple as Map.get(:mapped_function).(parameters). And when I unit test, I can swap out the function values for whatever I need.

5 Likes

There are a couple of strategies here:

  1. Use configuration files directly like shown here http://blog.plataformatec.com.br/2015/10/mocks-and-explicit-contracts/
  2. Use a dependency registry like shown here https://github.com/BlakeWilliams/pact
  3. Use the Reader monad like shown here https://github.com/rmies/monad/blob/develop/test/monad/reader_test.exs, and a blog post here http://blog.originate.com/blog/2013/10/21/reader-monad-for-dependency-injection/ (this is a scala example but you will get the idea)
3 Likes