Skip to content

LuaUnit Tests

LuaUnit Tests are used to test Lua code. They work in the following workspace types:

  • Lua

Test Structure

Folder Structure

LuaUnit tests execute a tests/test.lua file that is injected into the learner's workspace. Authors do not need to add this folder or file.

Test File Structure

LuaUnit tests always start by importing the luaunit module and end by running the test suite:

lu = require('luaunit')

-- tests 

os.exit( )

Each test is defined as a global function with a name prefixed by test. The luaunit module provides various assertions, such as assertEquals and assertStrContains. A complete list of assertions is in the LuaUnit documentation. Most assertions except a final string argument that will be shown to learners if the test fails :

lu = require('luaunit')
-- Imagine that adder.lua is a learner file that defines the add function

function testAddPositive()
    lu.assertEquals(add(1, 1), 2, "Expected add(1, 1) to return 2")

os.exit( )

Example Tests

By default, Lua variables are global. If a learner defines a local variable, require cannot access it. Test defensively by always checking that a variable exists with assertNotNil.

lu = require('luaunit')

-- require() cannot access local variables, so check with assertNotNil() first
function testSomeFunction()
    lu.assertNotNil(add, 'Make sure to define a global function `add`')
    lu.assertEquals(add(1, 1), 2, 'Expected `add(1, 1)` to return 2')

function testSomeVariable()
    lu.assertNotNil(trio, 'Make sure to define a global variable `trio`')
    lu.assertEquals(trio, 3, 'Expected `trio` to equal 3')

-- assertStrContains uses Lua's pattern-matching, not regular expressions.
function testSomeString()
    lu.assertNotNil(telephone, 'Make sure to define a global variable `telephone`')
    lu.assertIsString(telephone, 'Expected `telephone` to be a string')
    lu.assertStrContains(telephone, '[%d%p]', true, 'Expected variable `telephone` to contain only digits and punctuation')


Other Guidelines

  • Actual code (real variable names, language syntax, etc. ) in feedback messages should be code-ticked (`)
  • Lua tests should follow Test standards.