Tuesday, December 25, 2007

My First OCaml Tests - So Close To Heaven!

Some time ago a a discussion in the testdrivendevelopment Yahoo-Group evolved around the concept of "testable languages". I thought about this for a while and came up with the idea that I want to be able to have expressions as first class citizens:

assertThat { assertThat(false) } abortsWith TestFailedException

Today I played a little with OCaml, sorted my functional programming skillz out, and finally arrived at my first test driven unit test environment for OCaml! Note that it's nearly what I wanted to be able to write, but unfortunately there's not enough syntactic sugar for lambda expressions (or I didn't find out, yet), so I'm stuck with using the quite ugly ( function () -> expression ) syntax. But hey, it's really close to heaven.

exception TestFailed
exception TestError

let failsWith expectedError expression =
try
expression ();
false
with error ->
expectedError = error

let isTrue expression: bool =
expression

let isFalse expression: bool =
not (expression)

let assertThat expression conditionMatchesOn =
if not (conditionMatchesOn (expression)) then
raise TestFailed
else
()

let _ = (
assertThat true isTrue;
assertThat (isTrue true) isTrue;
assertThat (not (isTrue false)) isTrue;

assertThat false isFalse;
assertThat (isFalse false) isTrue;

assertThat (TestFailed = TestFailed) isTrue;
assertThat (failsWith TestError (function () -> raise TestError)) isTrue;
assertThat (failsWith TestFailed (function () -> raise TestError)) isFalse;
assertThat
( function () -> assertThat false isTrue )
( failsWith TestFailed );

Printf.printf "OK\n";
);;

No comments:

Post a Comment