I have written the following function in F# which, given two points, returns a function representing the line which passes throught the two points:
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).
You presumably want to check that, for any inputs (x1, y1) and (x2, y2), that the resulting function satisfies the following properties:
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.
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.
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.