简体   繁体   English

在测试中有条件地启动GenServer

[英]Conditionally start GenServer in tests

I have implemented a GenServer that listens to an external message queue via long polling. 我已经实现了GenServer,它通过长时间轮询来侦听外部消息队列。 For that, I am starting the GenServer with the start of the application, ie within the start/2 function of my application.ex file I specified an extra child in the supervisor list: 为此,我以应用程序的开头启动GenServer,即在我的application.ex文件的start/2函数中,我在主管列表中指定了一个额外的子级:

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

This list is then started with: 然后,此列表开始于:

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

Now I have the problem that the GenServer is of course also started when I am running some (1) database setup with mix ecto.reset or (2) tests with mix test . 现在我有一个问题,当我运行某些(1)使用mix ecto.reset数据库设置或(2)使用mix test时,GenServer当然也会启动。

For the tests (2) I could, eg only add MyApp.MessageQueueGenServer to the children list if Mix.env != :test . 对于测试(2) ,例如,如果Mix.env != :test ,则只能将MyApp.MessageQueueGenServer添加到children列表中。

But what about (1) ? 但是(1)呢? How to avoid starting my GenServer when running mix ecto.reset / mix ecto.setup /etc.? 在运行mix ecto.reset / mix ecto.setup / etc。时如何避免启动GenServer?

I had the same issue and I have it resolved with a configuration parameter. 我遇到了同样的问题,并使用配置参数解决了该问题。

config/config.exs config / config.exs

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

config/dev.exs 配置/ dev.exs

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

config/test.exs config / test.exs

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

your server file 您的服务器文件

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

Sidenote: you might want to consider using modern style of children declaration , since Supervisor.Spec is deprecated, that way it would be even cleaner: 旁注:由于不推荐使用Supervisor.Spec ,因此您可能要考虑使用现代风格的children声明 ,这样它甚至会更加干净:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM