是否可以从多个路径获得 Elixir 的 Mix 加载源?

Is it possible to have Elixir's Mix load sources from more than one path?

我一直在疯狂地尝试在 Elixir 上使用基于配置的模拟。我已经定义了我的模拟模块并将它放在“test/”目录下的“.ex”文件中。然后,每当我 运行 “混合测试”时,它都无法加载模块。但是,如果我将模拟移动到“lib/”下,那么一切正常。所以我想知道我的配置和文件结构是否缺少某些东西,或者是否有办法告诉“mix”在“lib/”之外的另一个目录中查找源文件。

文件结构:

my_app/
 |
 + -- lib/
 |     my_lib.ex
 |     my_service.ex
 |
 + ---test/
 |     test_helper.ex
 |     my_service_mock.ex
 |     my_lib_test.exs
 |
 +----config/
       config.exs
       test.exs
       prod.exs
       dev.exs

config/dev.exs

import Config
config :my_app, my_service: MyApp.MyService

config/test.exs

import Config
config :my_app, my_service: MyApp.MyServiceMock

my_lib.ex

defmodule MyLib do
  @my_service Application.get_env(:my_app, :my_service)

  def do_something, do: @my_service.do_something_else
end

my_service.ex

defmodule MyApp.MyService do
  def do_something_else, do: { :ok, "Running business task" }
end

my_service_mock.ex

defmodule MyApp.MyServiceMock do
  def do_something_else, do: { :ok, "Faking business task" }
end

my_lib_test.ex

defmodule MyApp.MyLibTest do
  use ExUnit.Case

  alias MyApp.MyLib

  test "MyList.do_something/0 should do it's thing" do
    assert { :ok, "Faking business task" } = MyLib.do_something
  end
end

命令“mix test”失败并出现以下错误:

== Compilation error in file lib/my_lib.ex ==
** (UndefinedFunctionError) function MyApp.MyServiceMock.do_something_else/0 is undefined (module MyApp.MyServiceMock is not available)
    MyApp.MyServiceMock.do_something_else()
    lib/my_lib.ex:3: (module)
    (stdlib 3.14) erl_eval.erl:680: :erl_eval.do_apply/6

我是运行凝丹1.11.2.

好吧,我终于在 Elixir 论坛上找到了这个 post 的解决方案:https://elixirforum.com/t/load-module-during-test/7400

事实证明,“Mix.Project”中有一个指定源路径的变量:

所以在我的“mix.exs”中我做了以下事情:

  def project do
    [
      ...
      elixirc_paths: elixirc_paths(Mix.env),
      ...
    ]
  end

  defp elixirc_paths(env_name) do
    case env_name do
      :test -> ["lib", "test/mockery"]
       _ -> ["lib"]
    end
  end

当然,我添加了目录“test/mockery/”并将“MyApp.MyServiceMock”移到那里...