Skip to content

Testing

Thomas Harrison edited this page Mar 9, 2025 · 2 revisions

Tests are stored under the tests/ directory. Each test is a lua file prefixed with test_. Tests are executed by runtest.lua and supported by asserts, mocks and patch.

Creating a test

Add a lua file prefixed with test_ in the tests/ directory with the following.

local test = {}

function test.setup()
    -- optional, called before each case
end

function test.teardown()
    -- optional, called after each test case
end

function test.case1()
    local a = 1
    expect_eq(1, a, 'a must equal 1')
    assert_lt(2, a, 'a must be less than 2')
end

return test

A list of available asserts can be found in asserts.lua and asserts_extra.lua.

Assert vs Expect

For most, there are two variants prefixed with assert_ and expect_ (eg. assert_eq and expect_eq). Similar to gtest, the expect statements will only log the check if it fails while assert will stop execution of the case.

Mocks and Patch

Mocks can be created using MagicMock(). Two helper functions are patch and patch_local which can create mocks for global or local objects that are automatically reverted after a case runs.

function test.case1()
    local mock = MagicMock()
    mock(1, 2)
    assert_eq(1, mock.call_count)
    expect_eq(1, mock.args[1])
    expect_eq(2, mock.args[2])
end

function test.case2()
    local mock = patch('table.concat')
    mock.return_value = 'result'
    local res = table.concat({1, 2, 3}, ', ')
    expect_eq('result', res)
    assert_eq(1, table.concat.call_count)
    expect_arr_eq({1, 2, 3}, table.concat.args[1])
    expect_eq(', ', table.concat.args[2])
end

TODO - mock return values

TODO - mock calls

Clone this wiki locally