OCaml By Examples



The prime way of testing something in OCaml is to use _inline tests_. Note that inline tests can only exist in libraries.
 (name mylib)
You'll have to manually add the `inline_tests` field as well as the `ppx_inline_test` ppx.
  (pps ppx_inline_test)))


This test will succeed as long as it returns `true`.
let%test "some test" = true
This test will succeed as long as it returns a unit `()`.
let%test_unit "some other test" = ()
Inline tests can be embedded in a lot of places, for example, modules.
module A = struct
  let lower_than_5 x = x < 5

  let%test_unit _ = assert ( lower_than_5 3 )
Best practice is to "hide" tests and test helpers in their own `test_module`.
let%test_module _ = (module struct
    let%test _ = A.lower_than_5 8


$ opam install ppx_inline_test
Note that unfortunately, the output of `dune runtest` is **nothing** if tests pass, so it's not always clear if tests are actually working or not...
$ dune runtest
File "main.ml", line 12, characters 4-33: <<A.lower_than_5 8>> is false.
  in TEST_MODULE at file "main.ml", line 11, characters 0-72

FAILED 1 / 4 tests


 (name mylib)
To run a single test, you will have to manually add this line into the dune file. It will run ALL the tests in the file, but you can be more acurate by adding a colon a line number to the name of the file. Not pretty, but it works. Just remember to remove it when you're done.
   (flags -only-test main.ml))
  (pps ppx_inline_test)))
next: property tests