I’m trying to wrap my head around using mocks in Elixir. There are a lot of blog posts on the subject but I’m not seeing any that address my use cases.
(no need to recommend http://blog.plataformatec.com.br/2015/10/mocks-and-explicit-contracts/, read it a few times )
To be a bit more specific, here are my scenarios/questions:
I would like my integration tests to write-to/read-from the database. I don’t want my unit tests to touch the database. I’d like to use a mock for the persistence layer. How can I do this with Mox? It seems all the examples require one into an all-or-nothing commitment. You’re either using the DB or not.
On dependency injection… I don’t mind injecting a mock Repo in my unit tests but I don’t understand how that scales into intermediary modules when I have to test those. For example:
defmodule MyApp.Accounts do def list_users(repo \\ MyApp.Repo) do repo.all(User) end end defmodule MyApp.Dashboard do # do i inject MyApp.RepoMock here? i'd need to DI all these functions. how do i test with mocks in this context? # def get_the_world(repo \\ MyApp.Repo) <---- ??? def get_the_world() do so_many_users = MyApp.Accounts.list_users(repo) MyApp.AnotherContext.more_stuff_to_mock_stub(MyApp.DI1) MyApp.Context3.yup_more_goes_here(MyApp.DI2) ... end end
Would appreciate it if someone can explain how I can use Mox in unit tests and not in integration tests. Would also like to know how DI works without having to pass modules through multiple layers just to have precise control in my unit tests.