1

我正在尝试在 F# 中编写我的第一个通用函数,看起来我在这里缺少一些概念:

module Assert =
    let ThrowsException<'e : exn>  functionUnderTest  =
    try 
        let result = functionUnderTest
        printfn "fails"
    with 
    | :? 'e  ->  printfn  "succeeds"
    | _  -> printfn "fails"

标准输入(18,28):错误 FS0010:模式中出现意外符号“:”。应为“>”或其他标记。

我希望能够使用我的函数来测试是否引发了异常。

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")
4

1 回答 1

7

错误显示“预期的'>'”,因为类型约束采用'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"

有关详细信息,请参阅MSDN 上的约束。

于 2012-11-28T20:39:04.813 回答