简体   繁体   English

F#中的单元测试函数返回函数

[英]Unit test function returning function in F#

I have written the following function in F# which, given two points, returns a function representing the line which passes throught the two points: 我已经在F#中编写了以下函数,给出了两点,就返回了一个函数,该函数表示通过这两个点的线:

let getFunction (point1:float*float) (point2:float*float) =
    let x1 = fst point1
    let y1 = snd point1
    let x2 = fst point2
    let y2 = snd point2
    let m = (y2-y1)/(x2-x1)
    let n = y1-x1*m
    fun x -> m*x+n

I would like to unit test this function, but I haven't find how to do it, since I can't use a function in a equality assertion. 我想对该功能进行单元测试,但是由于我不能在等式断言中使用该功能,所以我没有找到如何做的测试。 I have thought about generating a secuence of random points and testing the application of the function against the expected result for each point, but I was wondering if there is a better way. 我曾考虑过要生成一个随机的点,然后针对每个点的预期结果测试该函数的应用,但是我想知道是否有更好的方法。

I would use a property-based testing approach (see http://fsharpforfunandprofit.com/pbt/ for an excellent introduction). 我将使用基于属性的测试方法(有关出色的介绍,请参见http://fsharpforfunandprofit.com/pbt/ )。

You presumably want to check that, for any inputs (x1, y1) and (x2, y2), that the resulting function satisfies the following properties: 您可能想检查一下,对于任何输入(x1,y1)和(x2,y2),结果函数是否满足以下属性:

  • f(x1) = y1 f(x1)= y1
  • f(x2) = y2 f(x2)= y2
  • f is linear f是线性的

If the function satisifies these, it must be correct. 如果功能满足这些要求,则必须正确。

You can check the first two easily. 您可以轻松检查前两个。 For the final property, you can pick some random x values to test. 对于最终属性,您可以选择一些随机x值进行测试。

Repeat for a selection of inputs, and you're done. 重复选择输入,即可完成。 As Carsten mentions, FsCheck can be used to automate testing these properties using a large number of randomly generated test cases. 正如Carsten所述,FsCheck可用于使用大量随机生成的测试用例自动测试这些属性。

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

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