In Clojure the unit under test is the function. Unit test coverage should test all public function that form the API of their respective namespace.
clojure.test
namespace provides a unit testing framework and is included in the Clojure library, so is available in all Clojure projects.
Test runners are used to run one or more tests in a project.
Simple principles for writing unit tests
- One
test
namespace for eachsrc
namespace - One
deftest
function for each function under test - Multiple
is
assertions for one function - Group assertions in
testing
and provide a meaningful description of that grouping, adding more information when reviewing test failures especially for larger code bases. - `are for testing similar functionality with different data sets
- Test private functions (or don't use them) through public functions of each namespace (minimize test churn and time to run all tests)
- Use generative testing to create less code and yet test with more extensive range of data
- Use test selectors to organize tests and optimize speed of test runs
Project structure with tests
By convention, separate src
and test
directories are used to hold the source code and the code that tests that source code.
For each source code file in src
there should be a corresponding file in test with the same name and _test
postfix.
For example, code to test the src/codewars/rock_paper_scissors.clj
is saved in the file src/codewars/rock_paper_scissors_test.clj
file.
Example project: CodeWars: Rock Paper Scissors
Source and Test Namespaces
As with file names, the namespaces for each test code file is the same as the source code it is testing, with a -test
postfix.
codewars/rock-paper-scissors
source code namespace will have a matching codewars/rock-paper-scissors-test
namespace.
Create Projects from templates
Project Examples: Code challenges with unit tests
- TDD Kata: Recent Songlist - simple tests examples
- Codewars: Rock Paper Scissors (lizard spock) solution -
and
examples - practicalli/numbers-to-words - overly verbose example, ripe for refactor
- practicalli/codewars-guides - deps.edn projects
- practicalli/exercism-clojure-guides - Leiningen projects
References
- Example based unit testing in Clojure - PurelyFunctional.tv