【发布时间】:2023-03-19 05:49:01
【问题描述】:
我想测试一个正在使用Task.async的函数
为了让我的测试通过,我需要在断言之前让它休眠100ms,否则在执行异步任务之前测试进程被杀死。
有没有更好的办法?
已编辑,添加代码示例:
我想测试的代码(大致):
def search(params) do
RateLimiter.rate_limit(fn ->
parsed_params = ExTwitter.Parser.parse_request_params(params)
json = ExTwitter.API.Base.request(:get, "1.1/search/tweets.json", parsed_params)
Task.async(fn -> process_search_output(json) end)
new_max_id(json)
end)
end
以及我已经编写的测试(仅使用睡眠调用)
test "processes and store tweets" do
with_mock ExTwitter.API.Base, [request: fn(_,_,_) -> json_fixture end] do
with_mock TwitterRateLimiter, [rate_limit: fn(fun) -> fun.() end] do
TSearch.search([q: "my query"])
:timer.sleep(100)
# assertions
assert called TStore.store("some tweet from my fixtures")
assert called TStore.store("another one")
end
end
end
【问题讨论】:
-
您能否向我们展示一个最小的失败示例来说明您想要进行的特定类型的断言?
-
示例代码将极大地帮助您提供一个好的答案。
-
好的,刚刚添加了代码示例
-
对我的代码的任何其他评论都可以:)(尤其是模拟部分)
-
如果不打算使用任务的结果,就不要使用Task.async/1,可以直接使用Task.start_link/1。
标签: elixir