我正在尝试用F#编写我的第一个泛型函数,看起来我在这里缺少一些概念:
module Assert =
let ThrowsException<'e : exn> functionUnderTest =
try
let result = functionUnderTest
printfn "fails"
with
| :? 'e -> printfn "succeeds"
| _ -> printfn "fails"
stdin(18,28):错误FS0010:模式中出现意外符号':'。预期'&gt;'或其他令牌。
我希望能够使用我的函数来测试是否引发了异常。
let myFunction=HttpClient.postDocRaw "http://notexisting.com/post.php" "hello=data"
Assert.ThrowsException System.Net.WebException myFunction
我想实现这个测试工具,所以如果有人有解决方案,那很好,但此外,我正在学习F#,我想知道在哪里出错我试着写这样的函数。
最终代码:
module Assert =
let ThrowsException<'e when 'e :> exn> functionUnderTest =
try
let actual = functionUnderTest()
printfn "succeeds"
with
| :? 'e -> printfn "succeeds"
| _ -> Assert.Fail()
[<TestClass>]
type HttpClientTest() =
[<TestMethod>]
member x.PostDataWrongUrl() =
Assert.ThrowsException<System.Net.WebException> (fun() -> HttpClient.postDocRaw "http://notexisting.com/post.php" "hello=data")
答案 0 :(得分:7)
错误显示“预期”&gt;'“,因为类型约束采用'T when 'T :> baseType
形式。你的代码应该是:
module Assert =
let ThrowsException<'e when 'e :> exn> functionUnderTest =
try
let result = functionUnderTest
printfn "fails"
with
| :? 'e -> printfn "succeeds"
| _ -> printfn "fails"
有关详细信息,请参阅Constraints on MSDN。