unit-testing - 如何在 f# 中为模式匹配创建 fsunit 测试?

标签 unit-testing f# pattern-matching fsunit

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

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

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

最佳答案

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

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"

关于unit-testing - 如何在 f# 中为模式匹配创建 fsunit 测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47946136/

相关文章:

F# 创建二维数组

java - 添加到 java.util.regex.Pattern 或合并它们

android - 如何在 IntelliJ IDEA 中创建测试模块来测试 Android 库

android - 在 MVP 中使用 Retrofit 测试 RxJava 调用得到通缉但未被调用

unit-testing - 在没有导出的情况下测试 typescript 模块

java - 混合容器/客户端模式下的 Arquillian 和 Selenium

xml - 使用 XMLReader 的 F# XML 解析

f# - F# 中的中介操作

javascript - 正则表达式和javascript,一些匹配消失了!

scala - 如何产生多个值?