Skip to content

Instantly share code, notes, and snippets.

@andypike
Created September 28, 2016 21:15
Show Gist options
  • Save andypike/70d6667889c2df77ddeb6f072619e83f to your computer and use it in GitHub Desktop.
Save andypike/70d6667889c2df77ddeb6f072619e83f to your computer and use it in GitHub Desktop.
# Real implimentations:
# =====================
#
# This isn't really testing anything but the point is, rather than
# reading the module to use from config and fixing the module for
# all tests here we inject the module in the function call and supply
# a default for normal operation. This is akin to dependency injection
# in OO. Not sure if this is a good idea but seems more flexible as
# different tests can pass in a different fake (if needed).
defmodule GitHub do
def fetch_repos(username) do
IO.puts "Getting #{username}'s repos for real!..."
# Do some HTTP to get a list of repos and return them
[]
end
end
defmodule MyModule do
def do_something(username, adapter \\ GitHub) do
adapter.fetch_repos(username)
end
end
# Test stuff
# ==========
defmodule FakeGithub do
@moduledoc """
A fake github module used only it tests to replace a real module
Use pattern matching to specifiy a different result set
"""
def fetch_repos("andypike") do
IO.puts "Faking list of repos for andypike"
["rectify"]
end
def fetch_repos("cloud8421") do
IO.puts "Faking list of repos for cloud8421"
["99-elixir-problems", "dragonfly-server"]
end
end
defmodule MyModuleTest do
use ExUnit.Case
test "returns the repos list for andypike" do
assert MyModule.do_something("andypike", FakeGithub) == ["rectify"]
end
test "returns the repos list for cloud8421" do
assert MyModule.do_something("cloud8421", FakeGithub) == ["99-elixir-problems", "dragonfly-server"]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment