Getting a Good Grasp of F# (仮)

関数型言語F#をもっと楽しみたい

F#のコードをユニットテストで検証する その2(xUnit)

xUnit.net を利用してVisual Studio 2013のテストエクスプローラーでユニットテストを実行してみます。

その準備として以下の xUnit.net および xUnit.net テストランナーの NuGet パッケージをプロジェクトにインストールします。

 NuGet パッケージ管理画面からインストール

f:id:pongitsune:20160213214520p:plain

xUnit.net を利用したコードの例
  1. module Sample1
  2. open Xunit
  3.  
  4. let countWordsInStr (str: string) : int =
  5.     let clist: char list = [ for c in str -> c ] // stringをcharの配列に変換
  6.     let rec inWord (curList: char list) (count: int) : int =
  7.         match curList with
  8.         | [(**)] -> count
  9.         | hd::tl when hd = ' ' -> inSpace tl count
  10.         |  _::tl               -> inWord  tl count
  11.     and inSpace (curList: char list) (count: int) : int=
  12.         match curList with
  13.         | [(**)] -> count
  14.         | hd::tl when hd = ' ' -> inSpace tl count
  15.         |  _::tl               -> inWord  tl (count + 1) // 空白→文字の遷移でインクリメント
  16.     inSpace clist 0
  17.      
  18. [<Fact>]
  19. let ``Word Count - Part0``() =
  20.     Assert.Equal(0,  countWordsInStr " ")
  21.  
  22. [<Fact>]
  23. let ``Word Count - Part1``() =
  24.     Assert.Equal(1,  countWordsInStr " aaa")    
  25.  
  26. [<Fact>]
  27. let ``Word Count - Part2``() =
  28.     Assert.Equal(2,  countWordsInStr "aaa bbbb")    
  29.  
  30. [<Fact>]
  31. let ``Word Count - Part3``() =
  32.     Assert.Equal(3,  countWordsInStr "aaa bbbb ccccccc ")
  33.    
  34. [<Fact>]
  35. let ``Word Count - Part4``() =
  36.     Assert.Equal(4,  countWordsInStr "a b c d")

4行目の countWordsInStr がテスト対象となる関数です。引数で与えられた文字列に含まれている単語数を数えます。ここではホワイトスペースのみを区切り文字として認識するように書いています。

6~15行目はこの関数内で使用するローカル関数です。let rec...and...の構文使って相互再帰(mutual recursion)する関数を2つ定義しています。16行目でこのローカル関数を使ってcountWordsInStr の戻り値を作り、そのまま返しています。

18行目以降の5つの関数がテスト用関数の定義になります。Factアトリビュートを付加した関数がテストランナーによって実行されます。xUnitAssert.Equal メソッドで引数に渡された二つの値が等しいかを検査しています。

注)8行目・13行目にある(**)はF#用コメントです。はてなブログでは角括弧が消えてしまうことがあるのでその対策として入れてあります。

Visual Studio2013のテストエクスプローラーの実行結果

f:id:pongitsune:20160213214246p:plain