如何解释基于属性的测试代码?

时间:2016-05-12 12:49:02

标签: f# property-based-testing

如何解释基于属性的测试代码?

我正在努力翻译以下代码段中的说明:

let myProperty = Prop.forAll fiveAndThrees <| fun number ->

    let actual = transform number

    let expected = "jbdhjsdhjdsjhsdglsdjlljh"
    expected = actual

Check.QuickThrowOnFailure myProperty

具体来说,我正在与后向管道运营商(即“&lt; |”)进行斗争。

以下是测试:

[<Fact>]
let ``FizzBuzz.transform returns FizzBuzz`` () =
    let fiveAndThrees = Arb.generate<int> |> Gen.map ((*) (3 * 5)) 
                                          |> Arb.fromGen

    let myProperty = Prop.forAll fiveAndThrees <| fun number ->

        let actual = transform number

        let expected = "jbdhjsdhjdsjhsdglsdjlljh"
        expected = actual

    Check.QuickThrowOnFailure myProperty

有人可以一步一步指导我这段代码的工作原理吗?

可以使用正向管道运算符(即“|&gt;”)重写吗?

1 个答案:

答案 0 :(得分:3)

此答案仅涵盖使用<|代替|>的原因。

以下是5个使用具有大功能的<|的示例。第六个示例是使用|>而不是<|来显示代码的外观。关键是,对于使用|>的第6个示例,您必须查看代码以查找主要函数funThatNeedsListAndFunc,但使用<|主要函数funThatNeedsListAndFunc是显而易见的。因此,当最后一个参数是函数并且您希望在主函数之后传递函数以便于理解时,通常会看到<|。就这样;不要读更多内容。

在阅读了Mark的博客之后,我还了解到<|对于移除( )周围的fun非常有用。使用( )的示例如示例7所示。

let funThatNeedsListAndFunc list func =
    func list

let func = List.sum
let list = Seq.toList { 0 .. 5}

let result1 = funThatNeedsListAndFunc list func

printfn "result1: %A" result1

let result2 = funThatNeedsListAndFunc list <| func

printfn "result2: %A" result2

let result3 = funThatNeedsListAndFunc list <| List.sum

printfn "result3: %A" result3

let result4 = funThatNeedsListAndFunc list <| 
    fun (list : 'a list) -> List.sum list

printfn "result4: %A" result4

let result5 = funThatNeedsListAndFunc list <| 
    fun (list : 'a list) -> 
        // This will be a long function
        let a = 1
        let b = 2
        let c = a * b
        let result = List.sum list
        let d = "more useless lines"
        let (e,f,g) = ("a", 15, 3.0)
        result

printfn "result5: %A" result5

let result6 = 
    fun (list : 'a list) -> 
        // This will be a long function
        let a = 1
        let b = 2
        let c = a * b
        let result = List.sum list
        let d = "more useless lines"
        let (e,f,g) = ("a", 15, 3.0)
        result
    |> funThatNeedsListAndFunc list

printfn "result6: %A" result6

let result7 = 
    funThatNeedsListAndFunc list (fun (list : 'a list) -> 
        // This will be a long function
        let a = 1
        let b = 2
        let c = a * b
        let result = List.sum list
        let d = "more useless lines"
        let (e,f,g) = ("a", 15, 3.0)
        result)

printfn "result7: %A" result7