ProductPromotion
Logo

Elixir

made by https://0x3d.site

GitHub - dashbitco/mox: Mocks and explicit contracts in Elixir
Mocks and explicit contracts in Elixir. Contribute to dashbitco/mox development by creating an account on GitHub.
Visit Site

GitHub - dashbitco/mox: Mocks and explicit contracts in Elixir

GitHub - dashbitco/mox: Mocks and explicit contracts in Elixir

Mox

hex.pm hexdocs.pm ci coverage

Mox is a library for defining concurrent mocks in Elixir.

The library follows the principles outlined in "Mocks and explicit contracts", summarized below:

  1. No ad-hoc mocks. You can only create mocks based on behaviours

  2. No dynamic generation of modules during tests. Mocks are preferably defined in your test_helper.exs or in a setup_all block and not per test

  3. Concurrency support. Tests using the same mock can still use async: true

  4. Rely on pattern matching and function clauses for asserting on the input instead of complex expectation rules

The goal behind Mox is to help you think and define the contract between the different parts of your application. In the opinion of Mox maintainers, as long as you follow those guidelines and keep your tests concurrent, any library for mocks may be used (or, in certain cases, you may not even need one).

See the documentation for more information.

Installation

Just add mox to your list of dependencies in mix.exs:

def deps do
  [
    {:mox, "~> 1.0", only: :test}
  ]
end

Mox should be automatically started unless the :applications key is set inside def application in your mix.exs. In such cases, you need to remove the :applications key in favor of :extra_applications or call Application.ensure_all_started(:mox) in your test/test_helper.exs.

Basic Usage

1) Add behaviour, defining the contract

# lib/weather_behaviour.ex
defmodule WeatherBehaviour do
  @callback get_weather(binary()) :: {:ok, map()} | {:error, binary()}
end

2) Add implementation for the behaviour

# lib/weather_impl.ex
defmodule WeatherImpl do
  @moduledoc """
  An implementation of a WeatherBehaviour
  """

  @behaviour WeatherBehaviour

  @impl WeatherBehaviour
  def get_weather(city) when is_binary(city) do
    # Here you could call an external api directly with an HTTP client or use a third
    # party library that does that work for you. In this example we send a
    # request using a `httpc` to get back some html, which we can process later.

    :inets.start()
    :ssl.start()

    case :httpc.request(:get, {"https://www.google.com/search?q=weather+#{city}", []}, [], []) do
      {:ok, {_, _, html_content}} -> {:ok, %{body: html_content}}
      error -> {:error, "Error getting weather: #{inspect(error)}"}
    end
  end
end

3) Add a switch

This can pull from your config/config.exs, config/test.exs, or, you can have no config as shown below and rely on a default. We also add a function to a higher level abstraction that will call the correct implementation:

# bound.ex, the main context we chose to call this function from
defmodule Bound do
  def get_weather(city) do
    weather_impl().get_weather(city)
  end

  defp weather_impl() do
    Application.get_env(:bound, :weather, WeatherImpl)
  end
end

4) Define the mock so it is used during tests

# In your test/test_helper.exs
Mox.defmock(WeatherBehaviourMock, for: WeatherBehaviour) # <- Add this
Application.put_env(:bound, :weather, WeatherBehaviourMock) # <- Add this

ExUnit.start()

5) Create a test and use expect to assert on the mock arguments

# test/bound_test.exs
defmodule BoundTest do
  use ExUnit.Case

  import Mox

  setup :verify_on_exit!

  describe "get_weather/1" do
    test "fetches weather based on a location" do
      expect(WeatherBehaviourMock, :get_weather, fn args ->
        # here we can assert on the arguments that get passed to the function
        assert args == "Chicago"

        # here we decide what the mock returns
        {:ok, %{body: "Some html with weather data"}}
      end)

      assert {:ok, _} = Bound.get_weather("Chicago")
    end
  end
end

Enforcing consistency with behaviour typespecs

Hammox is an enhanced version of Mox which automatically makes sure that calls to mocks match the typespecs defined in the behaviour. If you find this useful, see the project homepage.

License

Copyright 2017 Plataformatec
Copyright 2020 Dashbit

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Articles
to learn more about the elixir concepts.

Resources
which are currently available to browse on.

mail [email protected] to add your project or resources here 🔥.

FAQ's
to know more about the topic.

mail [email protected] to add your project or resources here 🔥.

Queries
or most google FAQ's about Elixir.

mail [email protected] to add more queries here 🔍.

More Sites
to check out once you're finished browsing here.

0x3d
https://www.0x3d.site/
0x3d is designed for aggregating information.
NodeJS
https://nodejs.0x3d.site/
NodeJS Online Directory
Cross Platform
https://cross-platform.0x3d.site/
Cross Platform Online Directory
Open Source
https://open-source.0x3d.site/
Open Source Online Directory
Analytics
https://analytics.0x3d.site/
Analytics Online Directory
JavaScript
https://javascript.0x3d.site/
JavaScript Online Directory
GoLang
https://golang.0x3d.site/
GoLang Online Directory
Python
https://python.0x3d.site/
Python Online Directory
Swift
https://swift.0x3d.site/
Swift Online Directory
Rust
https://rust.0x3d.site/
Rust Online Directory
Scala
https://scala.0x3d.site/
Scala Online Directory
Ruby
https://ruby.0x3d.site/
Ruby Online Directory
Clojure
https://clojure.0x3d.site/
Clojure Online Directory
Elixir
https://elixir.0x3d.site/
Elixir Online Directory
Elm
https://elm.0x3d.site/
Elm Online Directory
Lua
https://lua.0x3d.site/
Lua Online Directory
C Programming
https://c-programming.0x3d.site/
C Programming Online Directory
C++ Programming
https://cpp-programming.0x3d.site/
C++ Programming Online Directory
R Programming
https://r-programming.0x3d.site/
R Programming Online Directory
Perl
https://perl.0x3d.site/
Perl Online Directory
Java
https://java.0x3d.site/
Java Online Directory
Kotlin
https://kotlin.0x3d.site/
Kotlin Online Directory
PHP
https://php.0x3d.site/
PHP Online Directory
React JS
https://react.0x3d.site/
React JS Online Directory
Angular
https://angular.0x3d.site/
Angular JS Online Directory