Question

I have a property that tests a type can be successfully round tripped to JSON and back.

let roundTrip<'a when 'a : equality> (x: 'a) = (toJSON >> ofJSON) x = x

which I currently run by calling

Check.Quick roundTrip<TypeName>

What I would like is to be able to run this property over a list of types that I get through reflection (scanning my assembly for types I know need to be JSON serializable)

Is it possible to run this property for types I have in a list at runtime rather that needing to specify them all in my test?

Was it helpful?

Solution

Supposing all of your types either have a custom generator defined for them, or can be derived by the built-generators, all you really need to do is instantiate a MethodInfo of the roundtrip method for each type you want to test. Then there is an overload Check.Method which you call for each of the types. That will run the standard FsCheck tests as if you would've called the method with the type at compile time.

Something like: (sorry, uncompiled, but should be close)

type Marker = class end
let roundtrip<'a> = //as above
let checkForTypes (ts:seq<Type>) =
    let roundtripInfo = typeof<Marker>.DeclaringType.GetMethod("roundtrip")
    ts 
    |> Seq.map (fun t -> roundtripInfo.MakeGenericMethod([|t|])) 
    |> Seq.iter (fun m -> Check.Method(Config.Quick, m))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top