最近试着写了些F#代码。不过习惯了TDD的我心里感觉有点不踏实,是不是还缺点什么呢?对了,单体测试。经过一番搜索和调查我决定试试FsUnit。结合该框架的示例代码的学习备注如下。

(* 添加引用 *)
#r "FsUnit.NUnit.dll"
#r "nunit.framework.dll"
(* 导入命名空间 *)
open NUnit.Framework
open FsUnit

(* 定义被测类 *)
type LightBulb(state) =
     member x.On = state
     override x.ToString() =
             match x.On with
             | true    -> "On"
             | false -> "Off"

(*
首先通过Attribute定义了一个TestFixture。
Setup的时候生成一个LightBulb实例,初始状态为true。
该TestFixture包含了分别测试On属性和toString方法的两个测试方法。
测试方法的命名很有特色。测试断言通过使用管道也和自然语言很接近。
*)

[]
type ``Given a LightBulb that has had its state set to true`` ()=
     let lightBulb = new LightBulb(true)
     [] member x.
        ``when I ask whether it is On it answers true.`` ()=
                     lightBulb.On |> should be True
     [] member x.
        ``when I convert it to a string it becomes "On".`` ()=
                     string lightBulb |> should equal "On"

[]
type ``Given a LightBulb that has had its state set to false`` ()=
     let lightBulb = new LightBulb(false)
     [] member x.
        ``when I ask whether it is On it answers false.`` ()=
                     lightBulb.On |> should be False
     [] member x.
        ``when I convert it to a string it becomes "Off".`` ()=
                     string lightBulb |> should equal "Off"

FsUnit是一个面向F#的xUnit成员。有了这样一个单体测试框架,我们就可以更自信地写代码了。

参考链接: http://fsunit.codeplex.com/