<turbo-stream action="append" target="posts_list"><template>    <div class="postbit" id="242980" data-post-id="242980">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="trisolaran" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/trisolaran/120/23748_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  trisolaran
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<blockquote>
<p>My first stab was to use Application config to allow a url override, which I set at runtime in tests. Then (duh!) I realised this messed up async tests.</p>
</blockquote>
<p>Any reason why you can’t configure the url globally in <code>config/test.exs</code> ? If there is no reason, then that’s the easiest place to configure it, and tests should be able to run in <code>async</code> mode. If you can’t, then you’ll have to disable <code>async</code> for those tests or resort to the fancier solution suggested in the thread: <a href="https://forum.elixirforum.com/t/bypass-and-async-tests-with-ex-unit/45005/9" class="inline-onebox" rel="nofollow">Bypass and async tests with ex_unit - #9 by josevalim</a>. (I never tried it out, btw)</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="242980" data-batch-url="/posts/batch_likers">
                        1
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/testing-a-controller-that-makes-outside-api-calls/45992/22">Post #21</a>
	                </div>
	            </div>
              <div id="likers-container-242980" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="242980"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #21"></div>
  </section>
</div>
    <div class="postbit" id="242986" data-post-id="242986">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="crispinb" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/crispinb/120/22642_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  crispinb
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>The problem is the port each bypass process listens on. Configuring this globally results in async tests routing requests to the wrong bypass.</p>
<p>To save any more time spent messing about with this, I did initially set async to false. Then it nagged at me! So I went back and implemented something inspired by Jose Valim’s solution, which works fine.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="242986" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/testing-a-controller-that-makes-outside-api-calls/45992/23">Post #22</a>
	                </div>
	            </div>
              <div id="likers-container-242986" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="242986"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #22"></div>
  </section>
</div>
    <div class="postbit" id="242987" data-post-id="242987">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="trisolaran" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/trisolaran/120/23748_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  trisolaran
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Glad to hear you solved your issue! <img src="https://forum.elixirforum.com/images/emoji/apple/+1.png?v=15" title=":+1:" class="emoji" alt=":+1:" loading="lazy" width="20" height="20"></p>
<p>Still, if you find some time, could you please elaborate a bit more on what your problem exactly was? I’m curious because I always use the config-based approach and never had any issues.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="242987" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/testing-a-controller-that-makes-outside-api-calls/45992/24">Post #23</a>
	                </div>
	            </div>
              <div id="likers-container-242987" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="242987"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #23"></div>
  </section>
</div>
    <div class="postbit" id="242996" data-post-id="242996">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="crispinb" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/crispinb/120/22642_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  crispinb
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Sure. Bear in mind I’m new to most of this, so I might easily have missed something. But AFAIK I can’t put the bypassed url into the compile time test config (ie. <code>config/test.exs</code>), as I can’t get the port from bypass until runtime.</p>
<p>My initial approach was to try something like this in my ExUnit Case:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">
setup do

  bypass = Bypass.open()

  url = "http://localhost:#{bypass.port}"

  Application.put_env(:app, :api_endpoint, url)

 

  Bypass.stub(bypass, "GET", "/checklists/1.json", fn conn -&gt;

    Plug.Conn.resp(conn, 200, TestData.Load.list())

  end)

  {:ok, %{api_token: "token"}}

end

</code></pre>
<p>.. and then get the url out of the Application config in my API client module.</p>
<p>The problem here is that with the tests running async, the global <code>:api_endpoint</code> config writes get interleaved unpredictably, so the client module requests go to the wrong ports &amp; hence wrong stubs. The result is failing tests due to unexpected or no responses. Async and global rarely mix well …</p>
<p>This is the same issue axelson refers to here: <a href="https://forum.elixirforum.com/t/bypass-and-async-tests-with-ex-unit/45005/3" class="inline-onebox" rel="nofollow">Bypass and async tests with ex_unit - #3 by axelson</a></p>
<p>(Presumably, as you haven’t had any such problems, your setup must be a bit different from the above.)</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="242996" data-batch-url="/posts/batch_likers">
                        1
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/testing-a-controller-that-makes-outside-api-calls/45992/25">Post #24</a>
	                </div>
	            </div>
              <div id="likers-container-242996" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="242996"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #24"></div>
  </section>
</div>
    <div class="postbit" id="243007" data-post-id="243007">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="trisolaran" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/trisolaran/120/23748_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  trisolaran
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<aside class="quote no-group" data-username="crispinb" data-post="25" data-topic="45992">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/crispinb/48/22642_2.png" class="avatar"> crispinb:</div>
<blockquote>
<p>Sure. Bear in mind I’m new to most of this, so I might easily have missed something. But AFAIK I can’t put the bypassed url into the compile time test config (ie. <code>config/test.exs</code>), as I can’t get the port from bypass until runtime.</p>
</blockquote>
</aside>
<p>Yes, you can <img src="https://forum.elixirforum.com/images/emoji/apple/slight_smile.png?v=15" title=":slight_smile:" class="emoji" alt=":slight_smile:" loading="lazy" width="20" height="20"></p>
<p>This is what I do:</p>
<p>config/test.exs:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">config :app, :api_endpoint, "http://localhost:9999"
</code></pre>
<p>In your test:</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">setup do

  bypass = Bypass.open(port: 9999)
  ...
end
</code></pre>
<p>As you can see, by passing the <code>port</code> option, you can tell Bypass which port to use. This allows you to configure the URL globally. This test can now run asynchronously with other tests, as it doesn’t need to overwrite the global test configuration.</p>
<p>I hope this helps.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="243007" data-batch-url="/posts/batch_likers">
                        1
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/testing-a-controller-that-makes-outside-api-calls/45992/26">Post #25</a>
	                </div>
	            </div>
              <div id="likers-container-243007" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="243007"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #25"></div>
  </section>
</div>
    <div class="postbit" id="243096" data-post-id="243096">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="crispinb" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/crispinb/120/22642_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  crispinb
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<p>Thanks, yes, I had read in the docs you could pass a port, but need my tests completely isolated as some need different responses to the same calls.</p>
<p>Actually my first thought reading your post was ‘that couldn’t possibly work’ as multiple processes couldn’t bind the same port. But then I remembered these aren’t OS processes of course. I don’t know much about BEAM internals, but presumably it multiplexes over a single OS thread bound to a port. In any case, a port per Bypass process suits my situation better, at the cost of a little additional complexity.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="243096" data-batch-url="/posts/batch_likers">
                        0
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/testing-a-controller-that-makes-outside-api-calls/45992/27">Post #26</a>
	                </div>
	            </div>
              <div id="likers-container-243096" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="243096"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #26"></div>
  </section>
</div>
    <div class="postbit" id="243139" data-post-id="243139">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="trisolaran" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/trisolaran/120/23748_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  trisolaran
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<aside class="quote no-group" data-username="crispinb" data-post="27" data-topic="45992">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/crispinb/48/22642_2.png" class="avatar"> crispinb:</div>
<blockquote>
<p>Actually my first thought reading your post was ‘that couldn’t possibly work’ as multiple processes couldn’t bind the same port</p>
</blockquote>
</aside>
<p>To clarify: there’s never multiple processes attempting to bind to the same port in my example. There’s only one test process using port 9999, and that’s the one testing the API module.</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="243139" data-batch-url="/posts/batch_likers">
                        1
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/testing-a-controller-that-makes-outside-api-calls/45992/28">Post #27</a>
	                </div>
	            </div>
              <div id="likers-container-243139" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="243139"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #27"></div>
  </section>
</div>
    <div class="postbit" id="243407" data-post-id="243407">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="neuone" src="/assets/icons/user-9f439610.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  neuone
                    <span class="op-star" title="Thread Starter">
                      <img alt="OP" class="op-star-icon" src="/assets/thread-icons/thread-icon-thread-starter-df91e872.png" />
                    </span>
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<aside class="quote no-group" data-username="dimitarvp" data-post="10" data-topic="45992">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/dimitarvp/48/38664_2.png" class="avatar"> dimitarvp:</div>
<blockquote>
<p>Something like the following (or you can save them in CSV / XML / JSON and <code>File.read!</code> them inside the mocking functions):</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">test "whatever" do
  # You should obviously configure a special test implementation that uses `Mox`.
  # This is well-documented elsewhere.
  expect(ThirdPartyApi.Mocked, :get_exchange_rates, fn %{from: "USD"} -&gt;
    # put stuff in here that you got from the actual live / production API.
  end

  assert your_function_calling_the_3rd_party_api() == :desired_result
end
</code></pre>
</blockquote>
</aside>
<h4><a name="p-243407-question-1" class="anchor" href="#p-243407-question-1" aria-label="Heading link" rel="nofollow"></a>Question</h4>
<p>What are your thoughts of stubbing out all of the functions in a mock module with an <code>InMemory</code> implementations in another module? Instead of sprinkling fixtures across multiple test cases?</p>
<p>So the idea is I have a <code>Client</code> for the live version but I also have an <code>InMemory</code> module that will respond with fixtures of JSON I have downloaded.</p>
<h4><a name="p-243407-for-example-2" class="anchor" href="#p-243407-for-example-2" aria-label="Heading link" rel="nofollow"></a>For example</h4>
<p>Let’s say I have this controller I need to test and I need to mock <code>MyApp.Api.get_tweet/1</code> that is nested inside.</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">defmodule MyAppWeb.HomeController do

  use MyAppWeb, :controller
  action_fallback MyAppWeb.FallbackController

  def index(conn, params) do
    with {:ok, tweet} &lt;- MyApp.Api.get_tweet(params["user_id"]) do
        render(conn, "index.json", tweet: tweet)
    end
  end

end
</code></pre>
<h4><a name="p-243407-apibehaviour-the-behaviour-3" class="anchor" href="#p-243407-apibehaviour-the-behaviour-3" aria-label="Heading link" rel="nofollow"></a>ApiBehaviour - The behaviour</h4>
<pre data-code-wrap="elixir"><code class="lang-elixir">defmodule MyApp.Api.ApiBehaviour do
  @callback get_tweet(user_id :: String.t()) :: tuple()
end
</code></pre>
<h4><a name="p-243407-client-live-implementation-4" class="anchor" href="#p-243407-client-live-implementation-4" aria-label="Heading link" rel="nofollow"></a>Client - Live implementation</h4>
<pre data-code-wrap="elixir"><code class="lang-elixir">defmodule MyApp.Api.ApiClient do
  @behaviour MyApp.Api.ApiBehaviour

  @impl MyApp.Api.ApiBehaviour
  def get_tweet(user_id) do
    # omit ... fetches the live server
  end
end
</code></pre>
<h4><a name="p-243407-inmemory-fake-response-implementation-5" class="anchor" href="#p-243407-inmemory-fake-response-implementation-5" aria-label="Heading link" rel="nofollow"></a>InMemory - Fake response implementation</h4>
<pre data-code-wrap="elixir"><code class="lang-elixir">defmodule MyApp.Api.InMemory do
   @moduledoc """
   The response from  here are real JSON responses that
   have been downloaded and are accessed from the fixtures
   in the test directory.
   """
  @behaviour MyApp.Api.ApiBehaviour

  @impl MyApp.Api.ApiBehaviour
  def get_tweet(user_id) do: {:ok, user_json_response()}
  # I just need a user_id with 9999 to generate an error
  # Does not imply that a user_id of 9999 will return an error
  # I don't know if I should do this here
  # I just want a canned response of an error
  def get_tweet(user_id) when user_id = 9999 do: {:error, :not_found} 

  defp user_json_response() do
    # put stuff in here that you got from the actual live / production API
    # real JSON response would appear here
  end
end
</code></pre>
<h4><a name="p-243407-the-contextbound-6" class="anchor" href="#p-243407-the-contextbound-6" aria-label="Heading link" rel="nofollow"></a>The Context/Bound</h4>
<pre data-code-wrap="elixir"><code class="lang-elixir">defmodule MyApp.Api do
  def get_trip(user_id), do: api_impl().get_tweet(user_id)
  defp api_impl(), do: Application.get_env(:my_app, :api)
end
</code></pre>
<h4><a name="p-243407-testtest_helpersexs-7" class="anchor" href="#p-243407-testtest_helpersexs-7" aria-label="Heading link" rel="nofollow"></a>/test/test_helpers.exs</h4>
<pre data-code-wrap="elixir"><code class="lang-elixir">Mox.defmock(ApiMock, for: MyApp.Api.ApiBehaviour) # &lt;- Add this
Application.put_env(:my_app, :api, ApiMock) # &lt;- Add this
ExUnit.start()
</code></pre>
<h4><a name="p-243407-using-moxstub_with-within-setup-8" class="anchor" href="#p-243407-using-moxstub_with-within-setup-8" aria-label="Heading link" rel="nofollow"></a>Using <code>Mox.stub_with/</code> within setup</h4>
<p>In my <code>setup</code> I can use <code>Mox.stub_with/2</code> and put <code>MyApp.Api.InMemory</code> and write tests that would access the fixtures responses from <code>MyApp.Api.InMemory</code>.</p>
<p>I can even swap out <code>MyApp.Api.InMemory</code> for <code>MyApp.Api.ApiClient</code> to try out the real implementation.</p>
<pre data-code-wrap="elixir"><code class="lang-elixir">defmodule MyApp.HomeControllerTest do
  use MyApp.Web.ConnCase

  setup do
    Mox.stub_with(ApiMock, MyApp.Api.InMemory)
    :ok
  end

  describe "GET /100" do
    test "success, it gets the tweet", %{conn: conn} do
        conn = get(conn, "/100")
        assert conn.params["user_id"] == "100"
        assert {:ok, _} == json_response(conn, 200)
    end
    test "error, for unknown", %{conn: conn} do
        conn = get(conn, "/9999")
        assert conn.params["user_id"] == "9999"
        assert {:error, :not_found} == json_response(conn, 200)
    end
  end
</code></pre>
<p>The <code>MyApp.Api.InMemory</code> module looks appealing as that module can be the one central place for placing my json responses.  However something about it feels off. It’s too hidden maybe? I don’t have enough experience using mocks to know what I’m feeling.</p>
<h3><a name="p-243407-using-expect-9" class="anchor" href="#p-243407-using-expect-9" aria-label="Heading link" rel="nofollow"></a>Using expect</h3>
<pre data-code-wrap="elixir"><code class="lang-elixir">defmodule MyApp.HomeControllerTest do
  use MyApp.Web.ConnCase
  import Mox

  setup :verify_on_exit

  describe "GET /100" do
    test "success, it gets the tweet", %{conn: conn} do
    expect(ApiMock, :get_tweet,fn -&gt; args 
        assert args == "100"
        valid_json_response()
    end)
        conn = get(conn, "/100")
        assert conn.params["user_id"] == "100"
        assert {:ok, _ } == json_response(conn, 200)
    end
    test "error, for unknown", %{conn: conn} do
      expect(ApiMock, :get_tweet,fn -&gt; args 
        assert args == "100"
        error_response()
      end)
        conn = get(conn, "/9999")
        assert conn.params["user_id"] == "9999"
        assert {:error, _} == json_response(conn, 200) 
    end
  end

  # Put the response here
  defp valid_json_response() do
    # omit for more room
    # returning some {:ok, json}
  end

  # Put the response here
  defp error_response() do
    # omit for more room
    # returning some {:error, json}
  end
</code></pre>
<p>This approach requires you to put your responses in the test file, which can access the fixtures. Nothing wrong with this approach.</p>
<h2><a name="p-243407-feedback-10" class="anchor" href="#p-243407-feedback-10" aria-label="Heading link" rel="nofollow"></a>Feedback</h2>
<p>I like the idea of stubbing out all of the functions in a mock module like <code>MyApp.Api.InMemory</code> with real JSON responses.</p>
<p>I know this approach isn’t a new concept, but am I maybe thinking about <code>MyApp.Api.InMemory</code> usage incorrectly?</p>
<p>Looking for feedback on what could go wrong in the future if I approach it this way?</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="243407" data-batch-url="/posts/batch_likers">
                        1
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/testing-a-controller-that-makes-outside-api-calls/45992/29">Post #28</a>
	                </div>
	            </div>
              <div id="likers-container-243407" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="243407"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-standard-post cat-standard-post" title="Post #28"></div>
  </section>
</div>
    <div class="postbit" id="262197" data-post-id="262197">
  <section>
    <div class="post-wrap">


					<div class="post-header">
		        <div class="user-avatar">
		          <img alt="dimitarvp" src="https://forum.elixirforum.com/user_avatar/forum.elixirforum.com/dimitarvp/120/38664_2.png" width="120" height="120" />
		        </div>
					
						<div class="user-details">
		          <div class="user-name">
		            <h3>
                  dimitarvp
                  </h3>
		          </div>
						
						</div>
					
					</div>

	        <div class="thread-main">
	            <div class="post-body" data-turbo="false">
								<aside class="quote no-group" data-username="neuone" data-post="29" data-topic="45992">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://forum.elixirforum.com/letter_avatar_proxy/v4/letter/n/3da27b/48.png" class="avatar"> neuone:</div>
<blockquote>
<p>What are your thoughts of stubbing out all of the functions in a mock module with an <code>InMemory</code> implementations in another module?</p>
</blockquote>
</aside>
<p>Way too much work. Let’s not forget that tests are just a dev artifact e.g. we are covering our own asses to make sure production doesn’t blow up in our faces.</p>
<p>Have a stringent approach to quality but also be minimal. Identify the places in the code that gives you the most anxiety and start with them.</p>
<aside class="quote no-group" data-username="neuone" data-post="29" data-topic="45992">
<div class="title">
<div class="quote-controls"></div>
<img alt="" width="24" height="24" src="https://forum.elixirforum.com/letter_avatar_proxy/v4/letter/n/3da27b/48.png" class="avatar"> neuone:</div>
<blockquote>
<p>Let’s say I have this controller I need to test and I need to mock <code>MyApp.Api.get_tweet/1</code> that is nested inside.</p>
</blockquote>
</aside>
<p>Your approach is good. I like <code>mox</code> a lot but there’s also <a href="https://hexdocs.pm/mock/Mock.html" rel="noopener nofollow ugc"><code>mock</code></a> which I found <em>extremely</em> convenient. And then there’s also the idea of making your own mocks as you seemed inclined to do.</p>
<p>All are valid.</p>
<p>I had projects where Mox was too much trouble because adding contracts (<code>@behaviour</code>) post-factum to huge business logic modules was not trivial. But it’s pretty much perfect for the cases where you’re not interested in troubleshooting 3rd party API and are OK with your worker crashing and retrying a minute later. Which is no trivial amount of projects out there, by the way. For them Mox is a perfect fit.</p>
<p>I used Mock when I wanted to preserve maximum amount of the mocked library’s original code behaviour and only stub out the parts where it hits the network – Mox is not doing so well here, you can just ignore 1000 coding lines from the mocked library below and just return <code>{:ok, list_of_structs}</code> and be done with it. While that feels neat it might ignore too much context and it might conceal a bug you hit in production and can’t replicate locally.</p>
<p>I only once rolled my own mock and kind of regret it but it was a very interesting exercise. And it helped us back then because we wanted to ignore part of the library’s code but not all of it – for such partial applications Mox could have also worked by the way but it also meant we had to rewrite parts of the library and we didn’t want to do that.</p>
<p>So here’s the advice most programmers hate hearing: <strong>ItDepends™</strong>.</p>
<p>(RE: Mox’s helpers, I like both <code>expect</code> and <code>stub</code>.)</p> 
	            </div>

	            <div class="base-line">
	                <div class="thread-counters">
	                    <span class="thread-count count-likes js-likers-trigger" title="Likes" data-post-id="262197" data-batch-url="/posts/batch_likers">
                        1
                      </span>
                      <!-- <span class="thread-count js-solved-indicator" title="Marked as solution"></span> -->
	                </div>
	                <div class="go-to-post">
	                  <a title="Go to post" alt="Go to post" href="https://forum.elixirforum.com/t/testing-a-controller-that-makes-outside-api-calls/45992/30">Post #29</a>
	                </div>
	            </div>
              <div id="likers-container-262197" 
                   class="likers-container"
                   data-first-post="false"
                   data-batch-url="/posts/batch_likers">
                   <div class="likers-placeholder" 
                     data-likers-post-id="262197"
                     data-batch-url="/posts/batch_likers">
                  <div class="post-likers"></div>
                </div>
              </div>
	        </div>
			

    </div>

    <div class="triangle-top-right type-last-post cat-last-post" title="Last post!"></div>
  </section>
</div>
</template></turbo-stream><turbo-stream action="replace" target="load-more-container"><template><div id="load-more-container" class="load-more-container">
    <span class="all-loaded">— All posts loaded —</span>
</div></template></turbo-stream>