我正试图通过一个FsCheck的例子来研究一个有歧视联盟的类型,以便为我们更大的项目建立最佳实践。现在我从发电机得到零,我不知道为什么。在以下代码中,DataGen.containerGenerator为null。
namespace Container
open System
open Xunit
open FsCheck
module ContainerLibrary =
type [<Measure>] oz
type Container =
| Cup of Common
| Bowl of Common
and Common =
{ Volume :decimal<oz>
Weight :decimal}
module DataGen =
type Generators =
static member arbVolume =
FsCheck.Gen.choose (1, 16)
|> FsCheck.Gen.map(fun x -> (decimal x / 8.0M) * 1.0M<ContainerLibrary.oz>)
|> FsCheck.Arb.fromGen
FsCheck.Arb.register<Generators>() |> ignore
let bowlGenerator =
FsCheck.Gen.map2 (fun a b -> ContainerLibrary.Bowl( { Volume = a
Weight = b}))
(Generators.arbVolume.Generator)
(FsCheck.Arb.generate<decimal>)
let cupGenerator =
FsCheck.Gen.map2 (fun a b -> ContainerLibrary.Cup( { Volume = a
Weight = b}))
(Generators.arbVolume.Generator)
(FsCheck.Arb.generate<decimal>)
let containerGenerator =
Gen.oneof [bowlGenerator; cupGenerator]
module Tests =
[<Fact;>]
let ``01 : Containers must be no more than 20 oz`` () =
//Is this the best way to get one of something?
let c = FsCheck.Gen.sample 0 1 DataGen.containerGenerator |> Seq.head
Assert.NotNull (c)
答案 0 :(得分:2)
当我运行它时,它似乎不为null,即使我获得更多值。您使用的是哪个版本的FsCheck?
[<Fact;>]
let ``01 : Containers must be no more than 20 oz`` () =
//Is this the best way to get one of something?
Gen.sample 0 100 DataGen.containerGenerator |> Seq.iter(fun c -> printf "%A" c; Assert.NotNull (c))
无论如何,关于你正在做什么,有几点需要注意。
我已经重新考虑了你的例子,考虑了一些这些事情:
module DataGen =
open ContainerLibrary
//can't really register this one because of the measure, would override all decimal generatos
let volumeGenerator =
Gen.choose (1, 16)
|> Gen.map(fun x -> (decimal x / 8.0M) * 1.0M<ContainerLibrary.oz>)
let commonGenerator =
Gen.map2 (fun a b -> { Volume = a
Weight = b})
(volumeGenerator)
(Arb.generate<decimal>)
//in case you like applicative style, otherwise completely equivalent
let commonGeneratorAlternative =
(fun a b -> { Volume = a; Weight = b}) <!> volumeGenerator <*> Arb.generate<decimal>
let bowlGenerator = Gen.map Bowl commonGenerator
let cupGenerator = Gen.map Cup commonGenerator
let containerGenerator =
Gen.oneof [bowlGenerator; cupGenerator]
type Generators =
static member Container() = containerGenerator |> Arb.fromGen
module Tests =
open FsCheck.Xunit
open ContainerLibrary
//use PropertyAttribute from FsCheck.Xunit
//use the defined container generator - can also move this to module level
//other ways to parametrize
[<Property(Arbitrary=[|typeof<DataGen.Generators>|])>]
//thanks to PropertyAttribute can now just take container as argument
let ``01 : Containers must be no more than 20 oz`` (container:Container) =
match container with
| Cup common
| Bowl common -> common.Volume <= 20.0M<oz>
|> Prop.collect container //see the generated values in the output
输出如下内容:
好的,通过了100次测试。
1%杯{体积= 2.0M; 重量= -0.0000221360928858744815609M;}。 1%杯{体积= 1.8750M; 重量= 922337.20325598085121M;}。 等