代码之家  ›  专栏  ›  技术社区  ›  Tom

在测试中有条件地启动GenServer

  •  3
  • Tom  · 技术社区  · 7 年前

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

    children = [
        supervisor(MyApp.Repo []),
        supervisor(MyAppWeb.Endpoint, []),
        supervisor(MyApp.MessageQueueGenServer, [])
    ]
    

    然后,此列表从以下内容开始:

    Supervisor.start_link(children, [strategy: :one_for_one, name: MyApp.Supervisor])
    

    现在我有一个问题,当我运行一些 (1) 数据库设置 mix ecto.reset (2) 使用测试 mix test .

    用于测试 (2) 我可以,例如,只添加 MyApp.MessageQueueGenServer children 列出如果 Mix.env != :test .

    但是呢 (1) ? 如何避免在运行时启动GenServer 混合外星体。重置 / mix ecto.setup /等等。?

    1 回复  |  直到 7 年前
        1
  •  7
  •   Aleksei Matiushkin    6 年前

    我也有同样的问题,我已经用一个配置参数解决了。

    配置/配置。exs公司

    config :myapp, :children, [
      MyApp.Repo, MyAppWeb.Endpoint, MyApp.MessageQueueGenServer]
    

    配置/dev.exs

    # config :myapp, :childen [] # tune it for dev here
    

    配置/测试。exs公司

    config :myapp, :children, [
      MyApp.Repo, MyAppWeb.Endpoint]
    

    您的服务器文件

    children = [
      :myapp
      |> Application.get_env(:children)
      |> Enum.map(&supervisor(&1, [])
    ]
    

    旁注: 您可能需要考虑使用 modern style of children declaration 自从 Supervisor.Spec 不推荐使用,这样会更干净:

    children = Application.get_env(:myapp, :children)