我目前具有跟踪用户何时连接到频道以及用户何时离开频道的功能。这是从这里的 stackoverflow 答案实现的。
我编写了以下测试(参见 commit)来验证我的回调逻辑:
socket = subscribe_and_join!(socket, PostChannel, "post:#{post.id}")
assert (length Records.list_perceptions()) == 1
...
assert head.counter == 1
close(socket)
:timer.sleep(10) # Is this necessary?
assert (length Records.list_perceptions()) == 1
...
assert head.counter == 0
在没有延迟的情况下进行测试时,不会触发监视器回调。消除延迟后,我的测试断言失败,并且在测试完成后出现 GenServer 关闭错误:
00:48:10.496 [error] Task #PID<0.381.0> started from :post terminating
** (stop) exited in: GenServer.call(#PID<0.373.0>, {:checkout, #Reference<0.0.2.400>, true, 15000}, 5000)
** (EXIT) shutdown: "owner #PID<0.372.0> exited with: shutdown"
(db_connection) lib/db_connection/ownership/proxy.ex:32: DBConnection.Ownership.Proxy.checkout/2
(db_connection) lib/db_connection.ex:920: DBConnection.checkout/2
(db_connection) lib/db_connection.ex:742: DBConnection.run/3
(db_connection) lib/db_connection.ex:636: DBConnection.execute/4
(ecto) lib/ecto/adapters/postgres/connection.ex:105: Ecto.Adapters.Postgres.Connection.execute/4
(ecto) lib/ecto/adapters/sql.ex:243: Ecto.Adapters.SQL.sql_call/6
(ecto) lib/ecto/adapters/sql.ex:441: Ecto.Adapters.SQL.execute_or_reset/7
(ecto) lib/ecto/repo/queryable.ex:130: Ecto.Repo.Queryable.execute/5
(ecto) lib/ecto/repo/queryable.ex:35: Ecto.Repo.Queryable.all/4
(ecto) lib/ecto/repo/queryable.ex:76: Ecto.Repo.Queryable.one!/4
(udia) lib/udia_web/channels/post_channel.ex:79: UdiaWeb.PostChannel.leave/2
(elixir) lib/task/supervised.ex:85: Task.Supervised.do_apply/2
(stdlib) proc_lib.erl:247: :proc_lib.init_p_do_apply/3
Function: #Function<0.28181301/0 in ChannelWatcher.handle_info/2>
Args: []
有没有办法干净地测试我的功能而不会在我的测试用例中引入延迟?