a
|> privacy
|> issue

So, how can we test a private function? Should we? Let's not concern us with the latter question. Now, imagine the following:

defmodule TestableDefp do
  defmacro __using__() do
    quote do
      import Kernel, except: [defp: 2]
      import __MODULE__
    end
  end

  defmacro defp(fun, body) do
    def_macro = if function_exported?(Mix, :env, 0) && apply(Mix, :env, [:test]), do: :def, else: :defp
    quote, do: Kernel.unquote(def_macro)(unquote(fun), unquote(body))
  end
end

This will allow us to test defp whenever we use it and only in testing mode MIX_ENV=test.

defmodule AModule do
  use TestableDefp

  defp a_fun(), do: :ok
end

Why would you do that? I think you should not do that. There's probably a smelly code.

And now I finished an example of what not to do.


—


to go back