Skip to content

Instantly share code, notes, and snippets.

@akorobov
Last active December 12, 2015 04:59
Show Gist options
  • Save akorobov/4718367 to your computer and use it in GitHub Desktop.
Save akorobov/4718367 to your computer and use it in GitHub Desktop.
Unittesting in SML
fun toStr (xs:int list) = List.foldl (fn (i,s) => Int.toString(i) ^ " " ^ s) "" xs;
(* returns true if all test cases were successful, false otherwise *)
fun test name (results:bool list) : bool =
let fun checkT (t, (failed, total)) =
if t then (failed, total + 1) else ([total+1] @ failed, total + 1)
val (failed, total) = List.foldl checkT ([], 0) results
in case (failed, total) of
(x::xs, t) => (print ("> Failed " ^ name ^ " [" ^ toStr(failed) ^ "] (total " ^ Int.toString(t) ^")\n") ; false)
| (nil, t) => (print ("> Success " ^ name ^ " (total " ^ Int.toString(t) ^")\n"); true)
end
(* tests given funtion against list of test cases where each case is tuple (inputparam, result) *)
fun testD name f cases =
(test name o List.map (fn (i,r) => (f i = r) handle _ => false)) cases;
(* usage example *)
fun even i = (i mod 2) = 0;
test "evens" [
List.all even [1,2,3,4] = false,
List.all even [2,4] = true,
List.all even [] = true
];
(* testing with test case data *)
val filterEvenCases = [
([], []),
([1,2,3,4], [2,4])
];
testD "testFilterEven" (List.filter even) filterEvenCases;
exception Exn;
test "exception" [
(fn x => if even x then raise Exn else true) 2 handle Exn => true
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment