How to properly test Exceptions with FsUnit

房东的猫 提交于 2019-12-08 15:48:00

问题


I'm trying to figure out how to properly test exceptions with FsUnit. Official documentation states, that to test for exceptions I have to right something like this:

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

But, if I don't mark my test method with [<ExpectedException>] attribute it will always fail. Sounds reasonable because if we want to test for exceptions we have to add such attribute in C# + NUnit.

But, as long as I've added this attribute it doesn't matter what kind of exception I'm trying to throw, it will be always handled.

Some snippets: 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

My LogicModuleTest.fs

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

回答1:


Answer has been found. To test that exception was thrown I should wrap my function call in the next style:

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

because underneath #fsunit uses NUnit's Throws constraint http://www.nunit.org/index.php?p=throwsConstraint&r=2.5 … which takes a delegate of void, raise returns 'a




回答2:


If you want to test that a specific exception type is raised by some code, you can add the exception type to the [<ExpectedException>] attribute like so:

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

More documentation is available on the NUnit site: http://www.nunit.org/index.php?p=exception&r=2.6.2



来源:https://stackoverflow.com/questions/16261497/how-to-properly-test-exceptions-with-fsunit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!