Search code examples
erlangeunitmeck

How do I meck the same function with multiple sets of parameter values?


I'm trying to meck out a call to application:get_env, but I'm testing a function that calls it with two different sets of arguments.

I setup two separate meck:expect calls like this, but when the function I'm testing tries to call application:get_env(my_app, my_param_one) it fails and throws error:function_clause with undefined.

meck:expect(application, get_env, fun(my_app, my_param_one) -> {ok, "my_value_one"} end),
meck:expect(application, get_env, fun(my_app, my_param_two) -> {ok, "my_value_two"} end),

How can I meck out the same function, with differents sets of parameter values?


Solution

  • The second meck is overwriting the first.

    Whenever you define a function in Erlang by pattern-matching on different sets of values, you separate each set of patterns with a semicolon, like this:

    -module(sample).
    
    -export([create_greeting/2]).
    
    create_greeting("Grant", _Greeting) -> io:format("Good day sir!");
    create_greeting(Name, Greeting) -> io:format("~s, ~s!", [Greeting, Name]).
    

    Similarly, when you setup your meck statements, define the function once, but separate each set of patterns/arguments with a semicolon, like this:

    meck:expect(application, get_env, fun(my_app, my_param_one) -> {ok, "my_value_one"};
                                         (my_app, my_param_two) -> {ok, "my_value_two"}
                                      end),