Fl4m3Ph03n1x

Fl4m3Ph03n1x

Mox fails test that should pass

Background

I am trying to use Mox to replicate some simple interactions but I am failing test that should be passing (or so I think):

Code

After creating a basic hello world project I modified to the following:


defmodule Testmox do
  alias MyApp.Calculator.Impl, as: Calc

  def hello, do: "Hello #{inspect Calc.add(1, 1)}"
  def bye, do: "Bye #{inspect Calc.mult(2, 2)}"
end

Textmox uses a basic calculator module:

defmodule MyApp.Calculator do
  @callback add(integer(), integer()) :: integer()
  @callback mult(integer(), integer()) :: integer()
end

defmodule MyApp.Calculator.Impl do
  @behaviour MyApp.Calculator

  alias MyApp.Calculator

  @impl Calculator
  def add(x, y), do: x + y

  @impl Calculator
  def mult(x, y), do: x * y
end

As you see, nothing extraordinary here. Now onto the test!

defmodule CalculatorTest do
  use ExUnit.Case, async: true

  alias Testmox
  alias MyApp.Calculator.Impl, as: Calc

  import Mox

  # Make sure mocks are verified when the test exits
  setup :set_mox_global
  setup :verify_on_exit!

  test "invokes add and mult" do
    MyApp.CalcMock
    |> expect(:add, &Calc.add/2)
    |> expect(:mult, &Calc.mult/2)

    Testmox.hello()
    Testmox.bye()
  end
end

Problem?

This test fails, even though Calc.add and Calc.mult are being called in the hello and bye functions respectively. I have even set the mode to global, so other processes can use it, but it still fails the tests. What am I doing wrong?

EDIT: I have also changed test_helpers.ex:

ExUnit.start()
Mox.defmock(MyApp.CalcMock, for: MyApp.Calculator)

Marked As Solved

LostKobrakai

LostKobrakai

You don’t need to create an empty module. defmock will take care of creating the module, you just need to give it a name for it to use.

Also Liked

peerreynders

peerreynders

Going by the documentation it seems to fit the xUnit classification of Configurable Test Double.

LostKobrakai

LostKobrakai

Testmox.hello calls MyApp.Calculator.Impl.add not MyApp.CalcMock.add. In elixir there nothing, which would allow a library to change code, so Mox cannot dynamically alter what get’s called, so you need to find a way to make the implementation changeable on your own. The options for that are using the app env to configure the implementation, passing the implementation as argument to the function or some compile time magic if you don’t need to change the implementation at runtime.

The other problem is that you’re running the tests before running defmock in your test_helpers.exs.

Fl4m3Ph03n1x

Fl4m3Ph03n1x

So, this should work, right?

defmodule CalculatorTest do
  use ExUnit.Case, async: true

  alias Testmox
  alias MyApp.Calculator.Impl, as: Calc

  import Mox

  # Make sure mocks are verified when the test exits
  setup :set_mox_global
  setup :verify_on_exit!

  test "invokes add and mult" do
    Mox.defmock(Calc, for: MyApp.Calculator)

    expect(Calc, :add, &Calc.add/2)

    Testmox.hello()
  end
end

It doesn’t…

LostKobrakai

LostKobrakai

I still don’t see any code to make Testmox.hello call the module defined by Mox instead of calling the hardcoded implementation of MyApp.Calculator.Impl.

LostKobrakai

LostKobrakai

I think you don’t really get how Mox works yet. It doesn’t matter what you use as callback in expect() for the issues you’re having. Testmox.hello is hardcoded to call MyApp.Calculator.Impl.add, which means it’s never going to not call your actual implementation, which you probably don’t want to happen as you’re trying to mock it.

What Mox.defmock(Calc, for: MyApp.Calculator) is doing is creating a new module with the name you supply as the first argument. Mox can then assert if the functions on this new module are actually called and let it return the values by the callbacks you supply via expect. It does not somehow magically instrument existing implementations to do different things than before.

You last implemenation is does basically override your existing module with a new module, which is not what you want to do.

Where Next?

Popular in Questions Top

vonH
In asking this question I am more interested about the expressiveness of the language itself and less concerned about the availability of...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
makeitrein
Hey all, just started picking up Elixir last week and am writing a scraper as a learning project. Baby step #1 is extracting the number ...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
hpopp
To simplify some tasks at work, I wrote and published this package yesterday. It’s a simple macro that enables Access behaviour on struct...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

Other popular topics Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
malloryerik
Hi, this is for people who, like me, have had some friction using .html.heex templates in VSCode. The solution seems to be, in a hyphena...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New
magnetic
Hey :wave:t3: Elixir community, I’ve been learning Elixir, and working on some side projects. My editor of choice is VSCode, and althoug...
New

We're in Beta

About us Mission Statement