在测试中有条件地启动GenServer

Tom*_*Tom 1 elixir phoenix-framework

我已经实现了GenServer,它通过长时间轮询来侦听外部消息队列。为此,我以应用程序的开头启动GenServer,即在文件start/2功能中,我application.ex在主管列表中指定了一个额外的子级:

children = [
    supervisor(MyApp.Repo []),
    supervisor(MyAppWeb.Endpoint, []),
    supervisor(MyApp.MessageQueueGenServer, [])
]
Run Code Online (Sandbox Code Playgroud)

然后,此列表开始于:

Supervisor.start_link(children, [strategy: :one_for_one, name: MyApp.Supervisor])
Run Code Online (Sandbox Code Playgroud)

现在,我有一个问题,当我运行某些(1)数据库设置mix ecto.reset(2)测试时,GenServer当然也会启动mix test

对于测试(2),我可以,例如,仅添加MyApp.MessageQueueGenServerchildren列表中Mix.env != :test

但是(1)呢?运行mix ecto.reset/ mix ecto.setup/ etc。时如何避免启动GenServer ?

Ale*_*kin 5

我遇到了同样的问题,并使用配置参数解决了该问题。

config / config.exs

config :myapp, :children, [
  MyApp.Repo, MyAppWeb.Endpoint, MyApp.MessageQueueGenServer]
Run Code Online (Sandbox Code Playgroud)

配置/ dev.exs

# config :myapp, :childen [] # tune it for dev here
Run Code Online (Sandbox Code Playgroud)

config / test.exs

config :myapp, :children, [
  MyApp.Repo, MyAppWeb.Endpoint]
Run Code Online (Sandbox Code Playgroud)

您的服务器文件

children = [
  :myapp
  |> Application.get_env(:children)
  |> Enum.map(&supervisor(&1, [])
]
Run Code Online (Sandbox Code Playgroud)

旁注:您可能要考虑使用现代风格的childs声明,因为Supervisor.Spec已弃用,这样它会更加干净:

children = Application.get_env(:myapp, :children)
Run Code Online (Sandbox Code Playgroud)