OUnit is a unit test framework for OCaml loosely based on HUnit, a unit testing framework for Haskell.
With OUnit, as with JUnit, you can easily create tests, name them, group them into suites, and execute them, with the framework checking the results automatically.
The basic principle of a test suite is to have a file test.ml
which will contain the tests, and an OCaml module under test, named foo.ml
.
File foo.ml
:
(* The functions we wish to test *)
let unity x = x;;
let funix ()= 0;;
let fgeneric () = failwith "Not implemented";;
The main point of a test is to check that the function under test has the expected behavior. You check the behavior using assert functions. The most simple one is OUnit2.assert_equal
. This function compares the result of the function with an expected result.
The most useful functions are:
OUnit2.assert_equal
the basic assert functionOUnit2.(>:::)
to define a list of testsOUnit2.(>::)
to name a testOUnit2.run_test_tt_main
to run the test suite you defineOUnit2.bracket_tmpfile
that create a temporary filename.OUnit2.bracket_tmpdir
that create a temporary directory.
File test.ml
:
open OUnit2;;
let test1 test_ctxt = assert_equal "x" (Foo.unity "x");;
let test2 test_ctxt = assert_equal 100 (Foo.unity 100);;
(* Name the test cases and group them together *)
let suite =
"suite">:::
["test1">:: test1;
"test2">:: test2]
;;
let () =
run_test_tt_main suite
;;
And compile the module
$ ocamlfind ocamlc -o test -package oUnit -linkpkg -g foo.ml test.ml
An executable named "test
" will be created. When run it produces the following output:
$ ./tests
..
Ran: 2 tests in: 0.00 Seconds
OK
When using OUnit2.run_test_tt_main
, a non zero exit code signals that the test suite was not successful.
(Source)