Search code examples
functionmockingerlangmeck

How to meck:expect a function with multiple arities


I have a function in a module which has multiple function clauses for the same function name but different function arities.

Example:

-module(module_name).

-export([func/1, func/2, func/3]).

func(N) ->
    N.

func(N, K) -> 
    N * K.

func(N, K, M) ->
    N * K * M.

I would like to mock this function for testing purposes so that instead of multiplying the numbers it adds them.

I know how to mock a function only for one arity:

1> meck:expect(module_name, func, fun(N, K, M) -> N + K + M end).

But how can I mock it for multiple arities?


Solution

  • In Erlang, functions with the same name and different arities are not considered clauses of the same function, but completely different functions. The names func/1, func/2 and func/3 hint at that.

    Meck works the same way, treating the three functions as different functions without any relationship between them. meck:expect determines the arity of the function to be mocked by inspecting the fun you pass to it, so you can just mock the three different functions like this:

    meck:expect(module_name, func, fun(N) -> N end).
    meck:expect(module_name, func, fun(N, K) -> N + K end).
    meck:expect(module_name, func, fun(N, K, M) -> N + K + M end).