我有一个名为Auth.app_id的函数,它尝试先从应用程序的配置中读取app_id,如果缺少,将查找system。
测试这种功能的最佳实践是什么?当然,在测试中预先使用Application.put_env和System.put_env是非常糟糕的做法,因为我们使用全局变量操作,而异步测试是不可能的。
test "getting config variables" do
Application.put_env(:appname, :app_id, "123")
assert Auth.app_id === "123"
end
test "getting env variables" do
System.put_env("APPNAME_APP_ID", "111")
assert Auth.app_id === "111"
end以下是getter函数内部的外观:
def app_id do
Application.get_env(
:appname,
:app_id,
System.get_env("APPNAME_APP_ID")
)
end问题是,我有很多函数使用这些getter,比如以app_id作为param返回url。
发布于 2016-03-04 10:49:31
这些变量是全局的,这是无法回避的(而不是嘲笑)。我的建议是,要么不同时运行测试(在use ExUnit中不使用async: true ),要么不测试app_id/0函数(因为它非常琐碎)。
发布于 2017-05-11 10:37:30
正如你所说的,你无法回避这些变量是全局的,所以我要做的是孤立这个问题:
app_id测试隔离到他们自己的测试文件中,使用async: false进行测试,并按照您已经完成的方式进行测试;app_id的值,那么也要这样做;app_id但app_id的实际值不影响结果的测试,在setup_all回调中设置一个合理的值,以便这些值只为整个测试文件设置一次。这样,大多数测试都可以运行异步,并且只有那些直接依赖于app_id值的测试才能运行非异步。
发布于 2020-06-04 21:09:44
我也有过类似的情况,最后用了这样的方法:
defmodule MyApp.ConfigTest do
use ExUnit.Case, async: false
setup do
previous_env = System.get_env()
on_exit(fn -> System.put_env(previous_env) end)
end
test "I can change environment for this test only" do
System.put_env("HOME", "/tmp")
assert System.get_env("HOME") == "/tmp"
end
test "Should not affect other tests" do
assert System.get_env("HOME") != "/tmp"
end
end重要的是on_exit回调和async: false定义。
我不能百分之百确定这是安全的,甚至是漂亮的TBH。
https://stackoverflow.com/questions/35793871
复制相似问题