Mocks on which you can set expectations of how they are called. And check those expectations were true.
Author oxinabox
3 Stars
Updated Last
2 Years Ago
Started In
October 2017


Build Status Build status

This package exists to help you make testing stubs. Its not to help you do patch mocks into code: for that see Mocking.jl. The stubs created using ExpectationStubs are suitable for patching in with Mocking.jl.

These stubs are ideal for if you already have dependency injection of functions set up.

We consider for the purpose of this package a stub to be a simplified function that returns a fixed value for a fixed input. Expectation Stubs is all about the Arrange, Act, Assert style of unit testing:

  • Arrange: setup expectations of how the stubbed out code will be called, and what it should return
  • Act: call the function being tested (which will then hit the stubbed out methods)
  • Assert: test that the stubs were tiggered in the way you expected, thus validating your belief about how things are used.

There are 5 key functions (check their docstrings on the REPL).

  • @stub foo: declares a stub called foo
  • @expect foo(::Integer, 8.5)=77: sets up an expectation that foo will be called with an Integer and the exact value 8.5. and if so it is to return 77
  • @used foo(100, ::Real) checks to see if foo was called with the the exact value 100 and something of type Real
  • @usecount foo(100, ::Real) as per @used except returns the number of times called
  • all_expectations_used(foo) checks that every expectation declared on foo was used (returns a Bool).

Example Usage

Lets say I have a function that checks on the status of say some pipe and if it has too much pressure, takes some response: normally calling a function called email

function check_status(pressure, its_bad_callback=email)
    if pressure > 9000
        its_bad_callback("phil@example.com", "Darn it Phil, the thing is gonna blow")
        return false

Now, when testing this function out, I don't want Phil to get 100s of emails. So I want to replace the its_bad_callback with some mock.

So I could write a little closure in my testing code, and have that closure set a variable and then check that variable, to see how it was called. And that is pretty good. But it is a bit adhock.

Enter ExpectationStubs.jl

using Base.Test
using ExpectationStubs

@testset "Check the pipe" begin
    @stub fakeemail
    @expect fakeemail("phil@example.com", ::AbstractString) = nothing # no return

    # check what happens if everything is OK
    @test check_status(1000, fakeemail) == true
    @test !@used fakeemail("phil@example.com", ::Any)
    ### Better not email Phil if everything is going ok.
    @test check_status(9007, fakeemail) == false
    @test @used fakeemail("phil@example.com", ::Any)

Required Packages

Used By Packages

No packages found.