简体   繁体   English

如何在f#中为模式匹配创建一个fsunit测试?

[英]How to create a fsunit test for pattern matching in f#?

I'm new to f# and fsUnit and I'm wondering how to test a pattern matching statement using fsUnit. 我是f#和fsUnit的新手,我想知道如何使用fsUnit测试模式匹配语句。 For example, if i have the following code how would you write a fsunit test for it? 例如,如果我有以下代码,你会如何为它编写一个fsunit测试?

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

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

First of all, you'd separate the code that implements the matching logic from the code that reads the input, because you can only test that the result of some call is correct: 首先,您将实现匹配逻辑的代码与读取输入的代码分开,因为您只能测试某些调用的结果是否正确:

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

Now you can write a series of tests that check that the string returned by handleInput is the string that you are expecting for each input: 现在,您可以编写一系列测试,检查handleInput返回的字符串是否是您希望每个输入的字符串:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM