我在Mac上运行F#,使用.NET Core2.0。
我有一个像这样的函数:
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有些陌生,我很难找到一个断言异常按预期抛出的工作示例。有人有吗?
发布于 2018-06-11 21:54:03
Expect.throws具有签名(unit -> unit) -> string -> 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让它发挥作用的一种方法是改变
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"现在期待是幸福的!

这个答案就是我思考它的方式。遵循类型签名通常是有帮助的。
编辑:我看到你的错误信息说This expression was expected to have type 'unit -> unit' but here has type 'char',所以我更新了我的答案,以匹配它。
https://stackoverflow.com/questions/50805319
复制相似问题