User Guide · mockagne

October 21, 2022 · View on GitHub

Introduction

Mockagne was originally written by Janne Sinivirta and Marko Pukari. It was created to help with testing of our mobile games written in Lua. It is now maintained by Sebastian Bär.

Mockagne name is a cross between mock and champagne, like it's Java big brother mockito. We are great fans of mockito and mockagne is heavily based on mockito's DSL.

Using mockagne

Creating and using mocks

Start by requiring mockagne and creating some local function references for better readability:

local mockagne = require "mockagne"

local when = mockagne.when
local any = mockagne.any
local verify = mockagne.verify

Then just create a mock instance for you:

t = mockagne.getMock()

Alternatively you can give your mock a speaking name, which comes in very handy should you need to debug test with mocks. Remember that Lua does not keep type information, so if you mock for example the products of an object factory you will have a hard time telling which mock got instantiated — unless of course you assigned a clear name which shows up in your debugger.

t = mockagne.getMock("My mocks speaking name")

Once you got the mock instance, you can invoke anything on the mock as if it was the real thing. Like:

t.foo()

Verifying calls to mocks

After your test has executed, you might be interested if a specific function on a mock was called. For example, to check if function foo() was call, you would simply say:

verify(t.foo())

Same works with parameters:

t.foo("bar")
verify(t.foo("bar"))

Returning values from mocks

If you want a call to t.foo() to return a value, you can teach the mock with:

when(t.foo("bar")).thenAnswer("baz")
print(t.foo("bar"))   -- this will print "baz"

Otherwise calls to mock methods will return nil.

More examples

For more examples, refer to mockagne_spec.lua that comes with. It contains all unit tests used to exercise mockagnes all features.

Installation

Easiest way to install mockagne is through luarocks. Just run

luarocks install mockagne

For manual installation, just add mockagne.lua to your package.path.