Fl4m3Ph03n1x
Background
I have some code that invokes a given function a certain number of times. I pass this function in the parameters so it is easy to stub.
However I need to know that under some conditions the function was called exactly X times. ExUnit.Case has an extremely limited support for this however, so I went ahead with the “send yourself a given message trick”
Code
@tag :wip
test "calls given function X times" do
my_pid = self()
deps = [
lookup_fn: fn _key ->
send(my_pid, :lookup)
{:ok, 1}
end
]
MyApp.do_work(deps)
# how to test I got the :lookup message exactly twice?
end
Research
The first easy solution is using receive multiple times:
receive do
msg -> assert msg == :lookup
end
receive do
msg -> assert msg == :lookup
end
receive do
msg -> assert msg == :lookup
end
# etc...
For example, if I wanted to check :lookup was called 10 times, I would have 10 receives.
This solution is very poor for 2 reasons:
- A ton of code repetition
- It doesn’t check that
:lookupwas called exactly X times, it checks it was received at least X times.
I searched for some libraries but couldn’t find anything. The closes thing I found was the SO question using macros:
Which I tried to adapt into an assert_receive_at_least (but failed miserably):
defmacro assert_receive_at_least(pattern, times, timeout \\ 500) do
quote do
defp loop(_pattern, current_times, total_times, _timeout) when current_times == total_times do
{:ok, :received}
end
defp loop(pattern, current_times, total_times, timeout) do
receive do
msg -> assert pattern == msg
after timeout -> {:error, :timeout}
end
end
defp run(pattern, times, timeout) do
loop(pattern, 0, times, timeout)
end
run(unquote(pattern), unquote(times), unquote(timeout))
end
end
Questions
- How do I check if a given message was received X times?
- How do I check if a given message was received at least X times?
- Are there any libraries that add decent stub support ?
Trending in Questions
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
Hello,
I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
Hi everyone,
I am toying with the idea of building a “match maker” for giving personal help to people that wants to start coding.
I sta...
New
Documentation
While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
So my question is quite simple and i have found no conclusive answer on forum, google or AI.
Should we use :erlang.float for Integer to ...
New
I recently noticed that Elixir’s Logger defaults its primary log level to :debug when no :logger, :level application configuration is pre...
New
I’m new to elixir and just tried to install the elixirLS extension for VScode(ium) and it is throwing some errors that I would like help ...
New
Other Trending Topics
Edit: 2026 May 15 - This post is archived.
Mob is alive!!
Main docs: mob v0.7.11 — Documentation
A bit of explanation for the slightly c...
New
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
I am happy to introduce the very α version of the new programming language compiled to BEAM.
Welcome Cure.
It has literally three kille...
New
Hi there! We created Gust: A task orchestrator inspired by Airflow.
For those who have never heard about Aiflow, it’s a Python-based wor...
New
Hi everyone!
The first release candidate for the Expert language server project is now available!
We’ve published a press release detai...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #ai
- #elixirconf-us
- #blog-post
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #elixirconf-eu
- #metaprogramming
- #hex










Showing Posts 1 to 10- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
LostKobrakai
shanesveller
I would encourage you to think about the problem differently if possible - are there existing, concrete side effects you can observe directly after the function has been called N times? Perhaps several new DB rows get created, a counter gets incremented, etc.
If you’ve read Mocks and Explicit Contracts and still want to continue with this path knowing those trade-offs and accepting them, Mox is a great choice. May require some refactoring to establish your contracts as a behaviour.
Fl4m3Ph03n1x
Could you elaborate a little bit more on your solution?
Also, I assume that is the solution to question 1. Would you be kind enough to suggest something about the second question?
This is precisely the things I don’t want to test. I want to test that the messages of my system were sent to its collaborators. I don’t wanna know what they did. This is a hallmark principle of good testing and good design I won’t abandon so easily.
I have read that article. In fact that article is the reason why I am injecting the dependencies via functional injection. First, because not every code benefits from the added noise of a contract, and second because José Valim himself suggests in the article that functional dependency injection is better.
But even if I were to use Mox, it would still fall (very) short of the basic features I need to test, such as meaningful stub and spies.
shanesveller
There is a fairly subtle important distinction between “was this function called N times”, which is a blatant implementation detail, and “was this message delivered N times”, which is still an implementation detail, but one that is likely to survive longer within your business domain than a function name. You can test the latter without any external libraries, depending on how your code is structured. Presumably the pid or registered name of your collaborator appears somewhere within your function arguments, and you can point that to another listener in various ways that would allow you to assert on the messages received.
Can you mention some of the shortcomings you found when trying the library? Have you opened any GitHub issues on the project to have them considered? It supports defining stubs and mocks based on anonymous or captured functions, and it would be fairly trivial to pass from that back into a “real” behavioral module to observe that the functions were called but still test the real behavior too.
amatalai
Maybe GitHub - appunite/mockery: Simple mocking library for asynchronous testing in Elixir. · GitHub would be better for your needs. It works well if you don’t need to check function calls between different processes (disclaimer: I am the author of this library, I can be biased)
peerreynders
It’s already covered.
for _ <- 1…x, do: assert_received :lookupthis will useassert_receivextimes. Ifxreceives do not happen, a timeout will fail the test.refute_received :lookupthis ensures that that there are no further receives beyondxfor the specified timeout.So combined the test ensures that exactly
xmessages were received within the specified timeouts.hauleth
If you are using OTP 21+ then you can write it as:
Fl4m3Ph03n1x
The function name is a detail, you are correct. I don’t care which specific function my code runs (if its name is A or B or whatever) but I do care that it runs the functions I inject on it a given number of times. This is the basics of testing (usually you test if a function was called once) and coulnd’t be farther from an implementation detail.
Allow me to showcase what a real test library is
https://sinonjs.org/releases/v7.2.4/
spies, stubs, fakes, mocks, timers, etc.
Admittedly they go out of the way with their own assertions (something which ExUnit could benefit from) but that’s another discussion.
A fair point, but one that I feel would be a waste of my time. I find it that Jose Valim would rather do other things then listening for a cry baby asking for features. Not only that, I need a solution I can use now, not a solution I can use in 4 months when the Elixir team finally has time to update Mox.
Ultimately, even though you are 100% logically correct, I still don’t engage in that course of action because I have a strong believe my efforts would be fruitless.
From the documentation I see a couple of profound limitations:
If I am incorrect, please feel free to en-light me
Checking it, thanks for popping in !
Using a global state ETS table on my tests truly is something I frown upon. My main issues with this approach are:
I will give it to you that your solution does technically work and that it may end up being less complex than the process approach. So it is something to have in mind. Thanks for sharing!
hauleth
No, you do not need to, as you are passing counter, which is unnamed and identified by reference.
Like most mocking libraries, fakes, etc. It just mean that sometimes it is just hidden from you. And if you want, you can always use
Agentinstead of:counters.Not exactly, just use unnamed ETS tables, and you will be good to go.
Fl4m3Ph03n1x
So I don’t have to keep track? Quite interesting.
A fair argument. Truth is as long as I can run my tests with
async: trueI don’t really care.Like the one
:counterscreate?You have overall good arguments and have convinced me.
Do you have any links or documentation to :counters.new ?
I check the official erlang docs but was unable to find anything.