Home > Uncategorized > Stateful testing in FsCheck

Stateful testing in FsCheck

FsCheck is a great test library for F#. I wrote about it back in 2011 but I really think it deserves more attention than it gets so here is another note. The documentation of FsCheck gives an example of stateful testing and I had a look at it today. Here is my slightly extended example for testing the StringBuilder class in .NET fx.

  1. open FsCheck
  2. open System.Text
  3.  
  4. let spec =
  5.     let appendString (s : string) =
  6.         { new Commands.ICommand<StringBuilder,string>() with
  7.             member x.RunActual c = c.Append(s)
  8.             member x.RunModel m = m + s
  9.             member x.Post (c,m) = m = c.ToString()
  10.             override x.ToString() = sprintf "appendString(%A)" s
  11.         }
  12.     let appendInt (i : int) =
  13.         {
  14.             new Commands.ICommand<StringBuilder,string>() with
  15.                 member x.RunActual c = c.Append(i)
  16.                 member x.RunModel m = m + i.ToString()
  17.                 member x.Post (c,m) = m = c.ToString()
  18.                 override x.ToString() = sprintf "appendInt(%A)" i
  19.         }
  20.     { new Commands.ISpecification<StringBuilder,string> with
  21.         member x.Initial() = (new StringBuilder(), "")
  22.         member x.GenCommand _ =
  23.             let stringGen = gen {
  24.                 let! s = Arb.generate<string>
  25.                 return appendString s
  26.             }
  27.             let intGen = gen {
  28.                 let! i = Arb.generate<int>
  29.                 return appendInt i
  30.             }             
  31.             Gen.oneof [ stringGen; intGen ]
  32.     }
  33.  
  34.  
  35. Check.Verbose (Commands.asProperty spec);;

 

Thanks to Paste as Visual studio code plugin to live writer.

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: