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( lu.LuaUnit.run() )
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
require('adder')
function testAddPositive()
lu.assertEquals(add(1, 1), 2, "Expected add(1, 1) to return 2")
end
os.exit( lu.LuaUnit.run() )
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('main')
-- 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')
end
function testSomeVariable()
lu.assertNotNil(trio, 'Make sure to define a global variable `trio`')
lu.assertEquals(trio, 3, 'Expected `trio` to equal 3')
end
-- assertStrContains uses Lua's pattern-matching, not regular expressions.
-- https://www.lua.org/pil/20.2.html
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')
end
os.exit(lu.LuaUnit.run())
Other Guidelines
- Actual code (real variable names, language syntax, etc. ) in feedback messages should be code-ticked (`)
- Lua tests should follow Test standards.