【问题标题】:How to create a fsunit test for pattern matching in f#?如何在 f# 中为模式匹配创建 fsunit 测试?
【发布时间】:2017-12-22 18:57:55
【问题描述】:

我是 f# 和 fsUnit 的新手,我想知道如何使用 fsUnit 测试模式匹配语句。例如,如果我有以下代码,您将如何为其编写 fsunit 测试?

let Menu () = 
    let Choice = Console.ReadLine()

        match Choice with
        | "A" | "a" -> Function1()
        | "B" | "b" -> Function2()
        | "C" | "c" -> Function3()
        | _ ->  Printfn"Error"

【问题讨论】:

  • 你测试函数,你测试任意代码块。

标签: unit-testing f# pattern-matching fsunit


【解决方案1】:

首先,您需要将实现匹配逻辑的代码与读取输入的代码分开,因为您只能测试某些调用的结果是否正确:

let handleInput choice = 
    match choice with
    | "A" | "a" -> Function1()
    | "B" | "b" -> Function2()
    | "C" | "c" -> Function3()
    | _ ->  "Error"

let menu () = 
    let choice = Console.ReadLine()
    let output = handleInput choice
    printfn "%s" output

现在您可以编写一系列测试来检查handleInput 返回的字符串是否是您期望每个输入的字符串:

handleInput "A" |> should equal "whatever Function 1 returns"
handleInput "b" |> should equal "whatever Function 2 returns"
handleInput "D" |> should equal "Error"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-24
    • 2021-02-21
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多