Testing Private Functions

I understand your point and I find it completely valid and right. However, I personally don’t write unit tests as documentation, and I also use ExUnit as a generic testing framework for property testing, behavior testing, performance testing, stress-testing, fuzzing etc. Even for functionality tests, I find it useful to be able to test private functions

For example, I have a module

defmodule Statistics do
  def top_users(source, amount) do
    source
    |> download()
    |> parse_stream()
    |> extract_users()
    |> calculate_rating()
    |> take_top(amount)
  end
  
  ...
end

All functions except top_users are private, because I don’t want other modules to rely on this logic. But I want to be able to test them to make sure that each step of this pipeline is free of errors and covers every corner case I come up with.

Other options are to

  1. Make these functions public (or move them to separate module). Then some other module might be able to call them, creating a dependency I don’t want
  2. Test only top_users. Then I will have to create an input for every possible corner-case, having a lot of work to do

Again, writing code in a way that you never have to test a private function, or writing a code in a way that every ExUnit test is more than just a test, but it is a documentation of the feature, is good and I accept these approaches. However, I prefer to write the code the other way and I prefer to set up the limits of the system myself

1 Like