Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/webpack/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
F# 应该如何断言异常_F#_.net Core_Expecto - Fatal编程技术网

F# 应该如何断言异常

F# 应该如何断言异常,f#,.net-core,expecto,F#,.net Core,Expecto,我在一台运行.NETCore2.0的Mac电脑上 我有一个函数如下所示: let rec evaluate(x: string) = match x with // ... cases | _ -> failwith "illogical" 我想编写一个Expecto测试,验证异常是否按预期抛出,大致如下: // doesn't compile testCase "non-logic" <| fun _ -> Expect.throws (evaluate "

我在一台运行.NETCore2.0的Mac电脑上

我有一个函数如下所示:

let rec evaluate(x: string) =
  match x with
  // ... cases
  | _ -> failwith "illogical"
我想编写一个Expecto测试,验证异常是否按预期抛出,大致如下:

// doesn't compile
testCase "non-logic" <| fun _ ->
  Expect.throws (evaluate "Kirkspeak") "illogical" 
错误是

此表达式应具有类型 'unit->unit',但这里有'char'类型

unit->unit让我觉得这类似于Assert.Fail,这不是我想要的

由于对F和Expecto有些陌生,我很难找到一个断言异常按预期抛出的工作示例。有人有吗?

Expect.throws有签名unit->unit->string->unit,所以要测试的函数必须是unit->unit,或者封装在unit->unit的函数中

let rec evaluate (x: string) : char =
  match x with
  // ... cases
  | _ -> failwith "illogical"
编译器错误告诉您传递给Expect.throws的函数尚未具有正确的签名

[<Tests>]
let tests = testList "samples" [
    test "non-logic" {
      // (evaluate "Kirkspeak") is (string -> char)
      // but expecto wants (unit -> unit)
      Expect.throws (evaluate "Kirkspeak") "illogical"
    }
]

[<EntryPoint>]
let main argv =
    Tests.runTestsInAssembly defaultConfig argv

现在expecto很开心

这个答案就是我思考的方式。遵循类型签名通常很有帮助


编辑:我看到你的错误消息,说这个表达式应该有'unit->unit'类型,但这里有'char'类型,所以我更新了我的答案以匹配它。

谢谢,这个答案的方向是正确的!但是,当我运行此代码时,不会捕获异常。您是针对.NET Framework还是.NET Core运行此功能?我在Mac电脑上,真奇怪。我从netcoreapp2.0控制台项目中提取了我在答案中输入的所有代码。您是否收到某种进一步的消息?是的,发生了异常:CLR/System.Exception tests.dll中发生了类型为“System.Exception”的异常,但未在用户代码中处理。测试时出现“不合逻辑”的异常。testingExceptions@121-1.InvokeUnit _arg1in/Users/../tests/tests.fs:Expecto.Expect.throwsFSharpFunc`2 f处的第121行,String message是否可以在github gist或其他文件中共享测试代码项目?我认为这听起来像是一些语法问题。否则,我不知道如何进一步帮助。如果有帮助,这里是我的来源。dotnet运行应该会导致我的屏幕截图。
Expect.throws (evaluate "Kirkspeak") "illogical"
// you could instead do (fun () -> ...)
// but one use of _ as a parameter is for when you don't care about the argument
// the compiler will infer _ to be unit
Expect.throws (fun _ -> evaluate "Kirkspeak" |> ignore) "illogical"