Unit testing custom types with %test_eq:

For context I am an ocaml beginner working through Types and Programming Languages.

I want to write inline tests using %test_eq as shown in real world ocaml, for example:

type colour = Red | Blue [@@deriving sexp, compare]

let%test "colours" = [%test_eq: colour] Red Blue

but I get the error:

16 | let%test "colours" = [%test_eq: colour] Red Blue
                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: This expression has type unit but an expression was expected of type
         bool

[%test_eq: <type>] is an “assertion”, i.e., it raises if the two arguments are not equal, rather than returning false. You could use let%test_unit instead, which runs the body of the test and considers the test to succeed if it does not raise any exceptions.

1 Like

Thank you for the instant reply, that worked a treat!