13

FsUnit で例外を適切にテストする方法を見つけようとしています。公式ドキュメントには、例外をテストするには、次のようなものを修正する必要があると記載されています。

(fun () -> failwith "BOOM!" |> ignore) |> should throw typeof<System.Exception>

[<ExpectedException>]しかし、テスト メソッドを属性でマークしないと、常に失敗します。例外をテストしたい場合は、C# + NUnit でそのような属性を追加する必要があるため、合理的に聞こえます。

ただし、この属性を追加している限り、スローしようとしている例外の種類は問題ではなく、常に処理されます。

いくつかのスニペット: My LogicModule.fs

exception EmptyStringException of string

let getNumber str =
    if str = "" then raise (EmptyStringException("Can not extract number from empty string"))
    else int str

私の LogicModuleTest.fs

[<Test>]
[<ExpectedException>]
let``check exception``()=
    (getNumber "") |> should throw typeof<LogicModule.EmptyStringException>
4

2 に答える 2

18

答えは見つかりました。例外がスローされたことをテストするには、関数呼び出しを次のスタイルでラップする必要があります。

(fun () -> getNumber "" |> ignore) |> should throw typeof<LogicModule.EmptyStringException>

#fsunit の下では、NUnit の Throws 制約 http://www.nunit.org/index.php?p=throwsConstraint&r=2.5を使用しているため、これは void のデリゲートを受け取り、raise は 'a を返します。

于 2013-04-28T12:45:17.203 に答える
3

特定の例外タイプが何らかのコードによって発生することをテストしたい場合は、次の[<ExpectedException>]ように属性に例外タイプを追加できます。

[<Test; ExpectedException(typeof<LogicModule.EmptyStringException>)>]
let``check exception`` () : unit =
    (getNumber "")
    |> ignore

その他のドキュメントは、NUnit サイト ( http://www.nunit.org/index.php?p=exception&r=2.6.2 ) で入手できます。

于 2013-04-28T12:44:50.387 に答える