首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何断言异常是预期的

如何断言异常是预期的
EN

Stack Overflow用户
提问于 2018-06-11 20:11:17
回答 1查看 980关注 0票数 4

我在Mac上运行F#,使用.NET Core2.0。

我有一个像这样的函数:

代码语言:javascript
复制
let rec evaluate(x: string) =
  match x with
  // ... cases
  | _ -> failwith "illogical"

我想编写一个Expecto测试,它验证异常是否按预期抛出,类似于:

代码语言:javascript
复制
// doesn't compile
testCase "non-logic" <| fun _ ->
  Expect.throws (evaluate "Kirkspeak") "illogical" 

错误是

这个表达式应该有类型'unit -> unit‘,但这里有'char’类型

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

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

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-06-11 21:54:03

Expect.throws具有签名(unit -> unit) -> string -> unit,因此您想要测试的函数必须是(单元->单元)或包装在函数(单元->单元)中。

代码语言:javascript
复制
let rec evaluate (x: string) : char =
  match x with
  // ... cases
  | _ -> failwith "illogical"

编译器错误告诉您,传递给Expect.throws的函数还没有正确的签名。

代码语言:javascript
复制
[<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

让它发挥作用的一种方法是改变

代码语言:javascript
复制
Expect.throws (evaluate "Kirkspeak") "illogical"

代码语言:javascript
复制
// 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',所以我更新了我的答案,以匹配它。

票数 6
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50805319

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档