Saturday, March 10, 2012

Sample in detail (write unit test)

In the Beta release, we published F# Beta samples. In the sample pack, there is a small one I’d like to dig into detail. Before Beta, hack is the only way to write unit test in F#. This sample was inspired by the recent post by Jack Fox. Why F# is good at unit test, because of its concise syntax and its functional nature. If you vision a function is a way transforming an input sequence to an output sequence, then F# is a perfect way to write unit test for a function.
For convenience, I created the following operators:
let inline (==) a b = Assert.AreEqual(a,b)
            let inline (!=) a b = Assert.AreNotEqual(a,b)
            let inline (===) a b = Assert.AreSame(a,b)
            let inline (?+) a = Assert.IsTrue(a)  //+ stands for TRUE
            let inline (?-) b = Assert.IsFalse(b) //- stands for FALSE
the ?+ and ?- are to test if a value is TRUE or FALSE.
let inline agreeTo sourceFunction targetFunction input =
        let source = input |> sourceFunction
        let target = input |> targetFunction
        let compareFunction a b = if a=b then 0 else -1
        let compareResult = Seq.compareWith compareFunction source target
        if compareResult <> 0 then failwith "sequence not equal"
The compare function is to compare two sequences are equal, the equal comparer is =. You can always add your comparing function to replace the default “=” function.
You can start an F# library project and put the sample code into the moduel1.fs. Because F# does not always specify the return value type, you have to make sure the function return type is F# type unit. If you happen to return something from the function, it won’t be picked up by the testing system. Please be very careful about this, I have been bitten several times and it is very easy to make such mistake in F#.
When everything compiles, you can use “unit test” -> “run unit tests” -> “all tests” to run your unit tests.

No comments: