gpt4 book ai didi

testing - 模拟函数 Elixir

转载 作者:行者123 更新时间:2023-11-28 21:00:54 26 4
gpt4 key购买 nike

我有这样的功能

def foo_bar() do
Enum.reduce_while(
image_options,
0,
fn image_option, _foo ->
case image_option["destination"] do
"s3" ->

case response = Upload.upload_on_s3(foo, bar) do
{:ok, _} ->
{:cont, {:ok, "ok"}}
{:error, _} ->
{:halt, response}
end
_ ->
{:cont, {:ok, "todo"}}
end
end
)

end

我想在单元测试中测试 foo_bar。我如何模拟 Upload.upload_on_s3(foo, bar) 函数?

最佳答案

您可以更改 foo_bar 以接受依赖项。下面我展示了一个带有默认参数的模块,但您可以省略默认参数,或者如果您愿意,也可以传递一个函数:

def foo_bar(upload_module \\ Upload) do
Enum.reduce_while(
image_options,
0,
fn image_option, _foo ->
case image_option["destination"] do
"s3" ->

case response = upload_module.upload_on_s3(foo, bar) do
{:ok, _} ->
{:cont, {:ok, "ok"}}
{:error, _} ->
{:halt, response}
end
_ ->
{:cont, {:ok, "todo"}}
end
end
)
end

然后,在你的单元测试中,你可以通过你自己的上传模块的假版本来获得你想要的行为。例如:

defmodule BadFakeUploader do
def upload_on_s3(_foo, _bar) do
{:error, "bad stuff"}
end
end

defmodule TestFooBar do
use ExUnit.Case

test "does the expected thing" do
assert whatever == SUT.foo_bar(BadFakeUploader)
end
end

关于testing - 模拟函数 Elixir ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46936479/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com