Search code examples
testingelixirerlang-otp

How to test an infinite, recursive Task in Elixir


Please check this code:

defmodule InfinitePollTask do
  def poll(opts \\ [])
    # function body code here
    poll(new_opts)
  end
end

I want to write a unit test for the function body code, assuming the function body perform some important computation using opts and produce a new_opts for the next iteration.


Solution

  • I'd just pull the computation out into a separate function that returns new_opts, and test that:

    defmodule InfinitePollTask do
      def poll(opts \\ [])
        poll(do_poll(opts))
      end
    
      def do_poll(opts)
        # important computation
      end
    end
    
    defmodule InfinitePollTaskTest do
      use ExUnit.Case
    
      test "some case" do
        assert InfinitePollTask.do_poll(some_opts) == some_result_opts
      end
    end