diff --git a/lib/mimic/module.ex b/lib/mimic/module.ex index eef9a74..3c22797 100644 --- a/lib/mimic/module.ex +++ b/lib/mimic/module.ex @@ -114,11 +114,20 @@ defmodule Mimic.Module do mimic_info = module_mimic_info() mimic_behaviours = generate_mimic_behaviours(module) mimic_functions = generate_mimic_functions(module) - quoted = [mimic_info | [mimic_behaviours ++ mimic_functions]] + mimic_struct = generate_mimic_struct(module) + quoted = [mimic_info, mimic_struct | mimic_behaviours ++ mimic_functions] Module.create(module, quoted, Macro.Env.location(__ENV__)) module end + defp generate_mimic_struct(module) do + if module.__info__(:struct) != nil do + quote do + defstruct unquote(for %{field: field} <- module.__info__(:struct), do: field) + end + end + end + defp module_mimic_info do quote do: def(__mimic_info__, do: :ok) end diff --git a/test/mimic_test.exs b/test/mimic_test.exs index cdde541..7eb07e1 100644 --- a/test/mimic_test.exs +++ b/test/mimic_test.exs @@ -945,4 +945,19 @@ defmodule Mimic.Test do assert_receive {:add, 1, 2} end end + + describe "structs" do + test "copies struct fields" do + struct_fields = + Structs.__info__(:struct) + |> Enum.map(&Map.get(&1, :field)) + + Mimic.copy(Structs) + + Structs + |> stub(:foo, fn -> :stubbed end) + + assert Structs.__info__(:struct) |> Enum.map(&Map.get(&1, :field)) == struct_fields + end + end end diff --git a/test/support/test_modules.ex b/test/support/test_modules.ex index 5dad55a..b7a2f9e 100644 --- a/test/support/test_modules.ex +++ b/test/support/test_modules.ex @@ -38,3 +38,9 @@ defmodule NoStubs do @moduledoc false def add(x, y), do: x + y end + +defmodule Structs do + @moduledoc false + defstruct [:foo, :bar] + def foo, do: nil +end