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

Execute some code when the mock is called #37

Closed
javflores opened this issue Jan 29, 2016 · 2 comments
Closed

Execute some code when the mock is called #37

javflores opened this issue Jan 29, 2016 · 2 comments

Comments

@javflores
Copy link

I have found quite handy sometimes to have the possibility to execute some code when the mock is called. One good use case is raising an exception when the mock is called.
In RhinoMocks there is something like this:

myStub
    .Stub(_ => _.Create(Arg<Invoice>.Is.Anything))
    .WhenCalled(_ => 
    {
        throw new Exception
    );

Is that possible with mock?
Thanks by the way for the nice library

@eproxus
Copy link

eproxus commented Feb 5, 2016

Yes, this is possible. As can be seen in the first example:

defmodule MyTest do
  use ExUnit.Case, async: false

  import Mock

  test "test_name" do
    with_mock HTTPotion, [get: fn(_url) -> "<html></html>" end] do
      HTTPotion.get("http://example.com")
      # Tests that make the expected call
      assert called HTTPotion.get("http://example.com")
    end
  end
end

The get function is replaced by another function entirely, in this case an anonymous function. You can either do whatever you want in there, e.g. [get: fn(url) -> my_code(url) end] or just reference another function you wrote that takes the same number of arguments, e.g. [get: &my_code/1].

@jjh42
Copy link
Owner

jjh42 commented Feb 7, 2016

Hopefully @eproxus answer resolved your question. Thanks.

@jjh42 jjh42 closed this as completed Feb 7, 2016
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