简体   繁体   中英

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. For example, if i have the following code how would you write a fsunit test for it?

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 "A" |> should equal "whatever Function 1 returns"
handleInput "b" |> should equal "whatever Function 2 returns"
handleInput "D" |> should equal "Error"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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