How to mock/stub methods in Elixir library Ecto/Repo?

Tell me please how to mock/stub methods of Repo module for my tests?

For ex.:

link = Repo.get_by(Link, short_url: url)
db_count = Repo.aggregate(Link, :count, :id)

I need that Repo.aggregate returns 10000000000 for my tests. The same with Repo.get_by .

How to do it?

And what is the best approach for module isolation in tests in Elixir?

Thanks!

There is bunch of mocking libraries out there:

These are the ones that I can recall from the memory, but for sure there are more of them out there.

1 Like

Thank you Jan!

But how to stub Repo methods in Mox?
I got an error:

module Shortly.Repo is not a behaviour, please pass a behaviour to :for

when run:

    test "generate correct short URL2" do
      Shortly.RepoMock
      |> expect(:aggregate, fn _, _, _ -> 100_000_000_000 end)

      assert UrlGenerator.uniq_url() |> String.length() == 5
    end

but if i add to test_helper:

defmodule Shortly.Repo do
  @callback aggregate(any(), any(), any()) :: any()
end

i get a lot of errors:

(UndefinedFunctionError) function Shortly.Repo.insert/1 is undefined or private

Already found the solution!

https://stackoverflow.com/questions/54967732/how-to-mock-stub-methods-in-elixir-library-ecto-repo/54968491#54968491