On this page

Unit Testing with alcotest (or ounit2) in OCaml

Published on August 3, 2026

Enrico Hochkoeppler Profile

By Enrico Hochkoeppler

Web Developer & TutoriaLibre Founder

A strong type system catches an entire category of mistakes before a program ever runs, but it says nothing about whether a function actually computes the right answer — that's what a test suite is for. Alcotest is the most widely used unit testing framework in the current OCaml ecosystem, with a lightweight, typed approach to writing assertions; OUnit2, an older xUnit-style alternative, remains a reasonable and still-maintained choice, especially for readers already familiar with JUnit-style testing from other languages.

Setting Up Alcotest​

Alcotest is installed like any other opam package and wired into a project through a test stanza:


(test

 (name test_stack)

 (libraries stack alcotest))

With this in place, dune test (equivalently, dune runtest) builds test_stack.ml and runs it as part of the project's test suite.

Testable Values and check​

Alcotest compares an expected value against an actual one using check, which needs to know both how to compare two values of a given type and how to print them when a test fails. This pairing of comparison and printing is called a testable, and Alcotest provides ready-made testables for every common type: Alcotest.int, Alcotest.string, Alcotest.bool, Alcotest.list Alcotest.int, Alcotest.option Alcotest.string, and so on.


Alcotest.(check int) "sum of two and two" 4 (2 + 2)

The arguments, in order: the testable describing how to compare and print the value, a short description shown if the test fails, the expected value, and the actual value being checked. When the two don't match, Alcotest reports exactly which test failed, along with both the expected and actual values, printed using the testable's own printing logic.

Writing Test Cases and Grouping Them Into Suites​

A test case pairs a descriptive name with a function to run, plus a speed marker: `Quick for tests that should always run, or `Slow for tests that can be skipped with a command-line flag when a faster feedback loop is needed.


let test_push_pop () =

  let s = Stack.push 1 Stack.empty in

  match Stack.pop s with

  | Some (x, _) -> Alcotest.(check int) "popped value" 1 x

  | None -> Alcotest.fail "expected Some, got None"



let test_pop_empty () =

  Alcotest.(check bool) "empty stack pops to None" true (Stack.pop Stack.empty = None)

Test cases are grouped into named suites and handed to Alcotest.run, which is the entry point for the whole test executable:


let () =

  Alcotest.run "Stack tests"

    [ ( "core operations"

      , [ Alcotest.test_case "push then pop" `Quick test_push_pop

        ; Alcotest.test_case "pop on empty" `Quick test_pop_empty

        ] )

    ]

Alcotest.run takes the overall suite name, followed by a list of named groups, each containing its own list of test cases — this two-level structure is what produces Alcotest's grouped, readable test output, with related tests visually organized together rather than listed as one long flat sequence.

Testing That an Exception Is Raised​

Functions that are expected to raise an exception under certain conditions need a slightly different check, since there's no ordinary return value to compare:


let test_pop_raises_on_bad_input () =

  Alcotest.check_raises "invalid input raises Failure"

    (Failure "bad input")

    (fun () -> ignore (Stack.of_string "not a stack"))

Alcotest.check_raises runs the given function and confirms it raises exactly the expected exception, failing the test if it raises something else, or nothing at all.

Running the Suite​

dune test builds and runs every test stanza in the project, printing a colorful, condensed summary by default — only tests that fail have their full output actually shown, keeping a healthy test suite's output short and easy to scan. Alcotest also supports selecting a subset of tests directly from the command line, by suite name and test number, which is useful when iterating on one failing test without rerunning the entire suite each time.

An Alternative: OUnit2​

OUnit2 takes a more traditional, xUnit-style approach, built around a handful of custom infix operators and assert_equal:


open OUnit2



let test_push_pop _ =

  let s = Stack.push 1 Stack.empty in

  match Stack.pop s with

  | Some (x, _) -> assert_equal 1 x

  | None -> assert_failure "expected Some, got None"



let test_pop_empty _ =

  assert_equal true (Stack.pop Stack.empty = None)



let suite =

  "Stack tests"

  >::: [ "push then pop" >:: test_push_pop

       ; "pop on empty" >:: test_pop_empty

       ]



let () = run_test_tt_main suite

>:: pairs a test name with its function, >::: groups several named tests into one suite, and run_test_tt_main is the entry point that actually executes them, exiting with a non-zero status if any test fails. Every OUnit2 test function receives a test context as its argument — ignored with _ in tests that don't need it — which can carry configuration or command-line parameters for more advanced setups.

Choosing Between Them​

Alcotest's typed testable system means a comparison and its failure-message printing are defined together, once, for a given type, and reused consistently across every test that needs it — a genuine advantage once a project accumulates enough custom types that comparing and printing them correctly starts to matter. Its output is also generally considered more readable by default, with grouped, colorized results. OUnit2's assert_equal is more familiar to anyone coming from xUnit-style frameworks in other languages, and remains a perfectly reasonable, actively maintained choice, particularly for smaller projects or teams already comfortable with that style. Both integrate identically well with Dune's test stanza, and switching between them later mainly means rewriting the assertions themselves, not restructuring how the project is built.

Key Takeaways​

Found this helpful? Share the knowledge...

... or support this project to keep it alive!

Buy Me a Coffee

Previous

OPAM Package Discovery & Installation

Next

Documentation Generation