From 871c520316dae452d087e34d63c3266cbbfa3719 Mon Sep 17 00:00:00 2001 From: "Paulo F. Oliveira" Date: Thu, 13 Jun 2024 19:04:04 +0100 Subject: [PATCH] Return `{:error, :already_mocked}` when using `new/1,2` over mock (#25) --- lib/nuntiux.ex | 13 +++++++++++-- test/nuntiux_test.exs | 9 +++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/lib/nuntiux.ex b/lib/nuntiux.ex index 119b0ba..85f32d4 100644 --- a/lib/nuntiux.ex +++ b/lib/nuntiux.ex @@ -89,9 +89,15 @@ defmodule Nuntiux do when process_name: process_name(), opts: opts(), ok: :ok, - error: {:error, :not_found} + error: {:error, :not_found | :already_mocked} def new(process_name, opts \\ %{}) do - Nuntiux.Supervisor.start_mock(process_name, opts) + case mocked_process(process_name) do + {:error, :not_mocked} -> + Nuntiux.Supervisor.start_mock(process_name, opts) + + _pid -> + {:error, :already_mocked} + end end @doc """ @@ -105,6 +111,9 @@ defmodule Nuntiux do {:error, :not_found} -> raise(Nuntiux.Exception, message: "Process #{process_name} not found.") + {:error, :already_mocked} -> + raise(Nuntiux.Exception, message: "Process #{process_name} is already mocked.") + :ok -> process_name end diff --git a/test/nuntiux_test.exs b/test/nuntiux_test.exs index 2a48f10..2988ac0 100644 --- a/test/nuntiux_test.exs +++ b/test/nuntiux_test.exs @@ -476,6 +476,15 @@ defmodule NuntiuxTest do assert captured_log =~ "expect_id: :no_head_matches" assert captured_log =~ ":function_clause" end + + test "new!/1 raises an exception if trying to mock a mock", %{ + plus_oner_name: plus_oner_name + } do + assert_raise(Nuntiux.Exception, ~r/^Process .* is already mocked\.$/, fn -> + Nuntiux.new!(plus_oner_name) + Nuntiux.new!(plus_oner_name) + end) + end end defp send2(dest, msg) do