Coder Social home page Coder Social logo

archan937 / mecks_unit Goto Github PK

View Code? Open in Web Editor NEW
55.0 7.0 7.0 45 KB

A simple Elixir package to elegantly mock module functions within (asynchronous) ExUnit tests using Erlang's :meck library

Home Page: http://elixirstatus.com/p/iXWw-mecksunit-elegantly-mock-module-functions-in-async-exunit-tests

Elixir 100.00%
elixir mocking exunit meck asynchronous elegant

mecks_unit's Introduction

MecksUnit Build Status

A simple Elixir package to elegantly mock module functions within (asynchronous) ExUnit tests using Erlang's :meck library

Installation

To install MecksUnit, please do the following:

  1. Add mecks_unit to your list of dependencies in mix.exs:

    def deps do
      [
        {:mecks_unit, "~> 0.1.9", only: :test}
      ]
    end

Usage

Mocking module functions is pretty straightforward and done as follows:

  1. Add use MecksUnit.Case at the beginning of your test file
  2. Use defmock as if you would define the original module with defmodule containing mocked functions
  3. Use mocked_test as if you would define a normal ExUnit test after having defined all the required mock modules
  4. Add MecksUnit.mock() in your test/test_helper.exs file
  5. Enjoy ;)

Please note that the defined mock modules only apply to the first mocked_test encountered. So they are isolated (despite of :meck having an unfortunate global effect) as MecksUnit takes care of it. Also, non-matching function heads within the mock module will result in invoking the original module function as well.

As of version 0.1.2, you can assert function calls using called (returns a boolean) or assert_called (raises an error when not having found a match) within your test block. Use _ to match any argument as if you would pattern match.

Prior to version 0.1.3, you would very often get :meck related compile errors when using MecksUnit in multiple test files. From that version on, this problem is solved. Happy testing! ^^

Define mock module for entire test case

As of version 0.1.8, you can "preserve" a mocked module definition for the rest of the test case by adding preserve: true.

defmock List, preserve: true do
  def wrap(:foo), do: [1, 2, 3, 4]
end

This behaviour is intended to be implemented as natural as possible. Therefore, you can override a preserved mock module once just by inserting a "regular" mock module definition:

defmock List, preserve: true do
  def wrap(:foo), do: [1, 2, 3, 4]
end

# mocked tests ...

defmock List do
  def wrap(:foo), do: ["this only applies to the next `mocked_test`"]
end

Also, you can override a preserved mock module for the rest of the test case by using preserve: true again.

defmock List, preserve: true do
  def wrap(:foo), do: [1, 2, 3, 4]
end

# mocked tests ...

defmock List do
  def wrap(:foo), do: ["this only applies to the next `mocked_test`"]
end

# mocked tests ...

defmock List, preserve: true do
  def wrap(:foo), do: [5, 6, 7, 8]
end

Please note that this behaviour is also tested in test/mecks_unit/preserve_test.exs.

A full example

The following is a working example defined in test/mecks_unit_test.exs

# (in test/test_helper.exs)

ExUnit.start()
MecksUnit.mock()
# (in test/mecks_unit_test.exs)

defmodule Foo do
  def trim(string) do
    String.trim(string)
  end
end

defmodule MecksUnitTest do
  use ExUnit.Case, async: true
  use MecksUnit.Case

  defmock String do
    def trim("  Paul  "), do: "Engel"
    def trim("  Foo  ", "!"), do: "Bar"
    def trim(_, "!"), do: {:passthrough, ["  Surprise!  !!!!", "!"]}
    def trim(_, _), do: :passthrough
  end

  defmock List do
    def wrap(:foo), do: [1, 2, 3, 4]
  end

  mocked_test "using mocked module functions" do
    task =
      Task.async(fn ->
        assert "Engel" == String.trim("  Paul  ")
        assert "Engel" == Foo.trim("  Paul  ")
        assert "Bar" == String.trim("  Foo  ", "!")
        assert "  Surprise!  " == String.trim("  Paul  ", "!")
        assert "MecksUnit" == String.trim("  MecksUnit  ")
        assert "Paul Engel" == String.trim("  Paul Engel  ", " ")
        assert [1, 2, 3, 4] == List.wrap(:foo)
        assert [] == List.wrap(nil)
        assert [:bar] == List.wrap(:bar)
        assert [:foo, :bar] == List.wrap([:foo, :bar])
        assert called List.wrap(:foo)
        assert_called String.trim(_)
      end)

    Task.await(task)
  end

  test "using the original module functions" do
    task =
      Task.async(fn ->
        assert "Paul" == String.trim("  Paul  ")
        assert "Paul" == Foo.trim("  Paul  ")
        assert "  Foo  " == String.trim("  Foo  ", "!")
        assert "  Paul  " == String.trim("  Paul  ", "!")
        assert "MecksUnit" == String.trim("  MecksUnit  ")
        assert "Paul Engel" == String.trim("  Paul Engel  ", " ")
        assert [:foo] == List.wrap(:foo)
        assert [] == List.wrap(nil)
        assert [:bar] == List.wrap(:bar)
        assert [:foo, :bar] == List.wrap([:foo, :bar])
      end)

    Task.await(task)
  end
end

Please note that you can delegate to the original implementation by either returning :passthrough (which forwards the given arguments) or return a tuple {:passthrough, arguments} in which you can alter the arguments yourself.

Asynchronous testing

Unlike Mock, MecksUnit supports running mocked tests asynchronously. W00t! ^^

License

Copyright (c) 2020 Paul Engel, released under the MIT License

http://github.com/archan937 โ€“ http://twitter.com/archan937 โ€“ [email protected]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

mecks_unit's People

Contributors

archan937 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

mecks_unit's Issues

Mocks are not found when running "mix test" with non-path arguments

Run tests with

mix test --trace

In that case, mix runs all the tests with more details. MecksUnit checks System.argv() and if there are any arguments, they are treated like path wildcards. Files resulting from that wildcards expansion are scanned for mocks. However, in the above case, the --trace argument is clearly not a file path, so no files are scanned for mocks, but all tests will run.

Possible fix ideas:

  • When the wildcards expansion results in empty list, fall back to the default wildcard pattern "test/**/*.exs". This still won't fix situations like mix test --exclude test/my_test.exs. In that case, all tests except for test/my_test.exs will run, but mocks will be looked for only in the test/my_test.exs.
  • Dig into ExUnit and find out if it's possible to hook into it to get the list of tests to be run before they actually run.

What do you think?

Problem with mockings

Hey!
I want to use this library though I am not entirely sure it fit my purpose.
I have created the below modules to show you my case:

defmodule Mocked do
  def func() do
    Mocked.ModuleA.call_module_b_func()
  end

  def func2() do
    Mocked.ModuleB.module_a_func()
  end
end
defmodule Mocked.ModuleA do
  alias Mocked.ModuleB

  def module_a_func() do
    :returns_from_module_a
  end

  def call_module_b_func() do
    ModuleB.module_b_func()
  end
end 

defmodule Mocked.ModuleB do
  alias Mocked.ModuleA

  def module_b_func() do
    :returns_from_module_b
  end

  def module_a_func() do
    ModuleA.module_a_func()
  end
end

and I try to run the following test which fails if I run both tests but succeeds when I run them separately.

defmodule MockedTest do
  use ExUnit.Case
  use MecksUnit.Case

  defmock Mocked.ModuleB do
    def module_b_func() do
      :returns_from_mocking
    end
  end

  defmock Mocked.ModuleA do
    def module_a_func() do
      :returns_from_mocking
    end
  end

  mocked_test "mocking works" do
    assert Mocked.func() === :returns_from_mocking
  end

  mocked_test "mocking works again" do
    assert Mocked.func2() === :returns_from_mocking
  end
end

Do you have any insights on this problem?

Thanks! ๐Ÿ™‚

Just one mock with "preserve" doesn't work

Hi all,

first of all, thanks for this great hex, it's looking really awesome! :-)

We noticed that the new preserve: true feature doesn't work if there's just one Mock defined in the test, for example:

defmodule Foo
  def bar(x), do: x
end

defmodule FooTest do
  use ExUnit.Case, async: true
  use MecksUnit.Case

  # defmock Foo do
  #   def bar(_x), do: 1
  # end

  defmock Foo, preserve: true do
    def bar(_x), do: 1
  end

  mocked_test "this should work" do
    assert Foo.bar(nil) == 1
  end

  mocked_test "this should work as well" do
    assert Foo.bar(nil) == 1
  end
end
mix test test/foo_test.exs 

FooTest
  * test this should work as well (2.9ms)

  1) test this should work as well (FooTest)
     test/foo_test.exs:17
     Assertion with == failed
     code:  assert Foo.bar(nil) == 1
     left:  nil
     right: 1
     stacktrace:
       test/foo_test.exs:18: (test)

  * test this should work (0.02ms)

  2) test this should work (FooTest)
     test/foo_test.exs:13
     Assertion with == failed
     code:  assert Foo.bar(nil) == 1
     left:  nil
     right: 1
     stacktrace:
       test/foo_test.exs:14: (test)



Finished in 0.04 seconds
2 tests, 2 failures

Randomized with seed 711881

By activating the first mock, the second one actually starts working.

Module attributes are not visible inside defmock block

Hello @archan937, thank you very much for this nice tool!

Using module attribute inside defmock gives a compilation error.
In test module:

@uuid UUID.generate()

defmock SomeApp.Repo do
    def get(SomeApp.Schema.Application, @uuid), do: %SomeApp.Schema.Application{}
end

In console:

> mix test

warning: undefined module attribute @uuid, please remove access to @uuid or explicitly set it before access
  nofile:106: SomeApp.RepoTest0.SomeApp.Repo (module)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.