Testing Task Async

Hi everyone,

I am trying to test a function where in it call an async task. For example:

def some_function() do
  Task.async(fn -> do_something() end)
  return "something else"

How am I going to test that do_something() is being called? Let’s just assume for this case I need to return “something else” and not the task pid.

Task.async needs to do something your test can observe. Most often people make the code in the async send a message to the test process or another location, which is known and can be observed.


So if I understand correctly, in this case, I will have to maybe create a module in test environment and make my Task.async() call that module which send a message to the test process instead?

Exactly. Mostly/the way I do it is to configure the module called once for the test environment and once for the other environments. You can then test that the Task.async executes the module, but still unit test the “real” module implementation. Best to make them both adopt the same behaviour to make sure nothing goes wrong.

Glancing over it, this blog post describes the interchangeable implementations I’m referencing: https://semaphoreci.com/community/tutorials/a-practical-guide-to-test-doubles-in-elixir