Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Mocking functions with optional arguments #74

Closed
youroff opened this issue Oct 5, 2017 · 7 comments
Closed

Mocking functions with optional arguments #74

youroff opened this issue Oct 5, 2017 · 7 comments

Comments

@youroff
Copy link

youroff commented Oct 5, 2017

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
Copy link
Contributor

spscream commented Oct 5, 2017

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
Copy link
Author

youroff commented Oct 6, 2017

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
Copy link
Contributor

spscream commented Oct 6, 2017

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
Copy link
Contributor

spscream commented Oct 6, 2017

But I think your variant with two entries would work

@spscream
Copy link
Contributor

@youroff I pushed some examples in my pr: #75 and it works :)

@Olshansk
Copy link
Collaborator

Merged #75.

@youroff Did you get it to work as expected?

@youroff
Copy link
Author

youroff commented Oct 15, 2017

Yup, thanks guys!

@youroff youroff closed this as completed Oct 15, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants