jjh42 / mock

Mocking library for Elixir language
MIT License
646 stars 81 forks source link

Mocking functions with optional arguments #74

Closed youroff closed 6 years ago

youroff commented 7 years ago

Variable amount of arguments is not allowed in lambda, how would one approach mocking a function with optional arguments then?

defmodule HigherMath do
  def times(x, m \\ 2), do: x * m # just some silly example
end
# .....
test "test_name" do
  with_mock HigherMath, [get: fn (x, m) -> :uh end] do
    times(3) # mock ignored, outputs 6
  end
end
spscream commented 7 years ago

You must mock both - get/1 if you calling it without arguments from code or both get/1 and get/2, if you using both variants of calling, because mocking makes module in background and defines functions which you passed to with_mock and knows nothing about module you are mocking. In example you define get/2, which creates the following module(I'm simplifying a bit now):

defmodule HigherMath do
  get(x, m) ->
    :uh
  end
end
youroff commented 6 years ago

Ok, but how mock definition would look like? Just two entries in a Keyword with the same key? Like this?

[get: fn (x) -> :ok end, get: fn (x, m) -> :ok end]
spscream commented 6 years ago

I don't know exactly how to do it using Mock, I personally using :meck directly. So using multiple calls to :meck.expect you could achieve what you want :)

spscream commented 6 years ago

But I think your variant with two entries would work

spscream commented 6 years ago

@youroff I pushed some examples in my pr: https://github.com/jjh42/mock/pull/75 and it works :)

Olshansk commented 6 years ago

Merged https://github.com/jjh42/mock/pull/75.

@youroff Did you get it to work as expected?

youroff commented 6 years ago

Yup, thanks guys!