Skip to content

Instantly share code, notes, and snippets.

@MikeMKH
Created May 18, 2014 18:50
Show Gist options
  • Save MikeMKH/783ef9b82d2987795be6 to your computer and use it in GitHub Desktop.
Save MikeMKH/783ef9b82d2987795be6 to your computer and use it in GitHub Desktop.
FizzBuzz in C# using FsCheck with XUnit to test.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FizzBuzz
{
public class FizzBuzzer
{
public string Translate(int value)
{
return new List<Tuple<Func<int, string, bool>, string>>
{
new Tuple<Func<int, string, bool>, string>(
(val,ret) => value%3 == 0, "Fizz"),
new Tuple<Func<int, string, bool>, string>(
(val,ret) => value%5 == 0, "Buzz"),
new Tuple<Func<int, string, bool>, string>(
(val,ret) => string.IsNullOrEmpty(ret), value.ToString())
}.Aggregate(string.Empty, (k, t) => Translator(t.Item1(value, k), t.Item2, k));
}
public static string Translator(bool test, string translation, string k)
{
return k + (test ? translation : string.Empty);
}
}
}
namespace FizzBuzzPropertyTests
// example of FsCheck showing different ways to restricted FizzBuzz testing
open Xunit
open FsCheck
open FsCheck.Xunit
open FizzBuzz
module ``FizzBuzz Property tests`` =
[<Fact>]
let ``NCrunch work``() =
()
// less restrictive tests
[<Property>]
let ``A number not be divisable by 5 and multiplied by 3 will return Fizz`` (x:int) =
let fizzbuzzer = FizzBuzzer ()
(x % 5 <> 0)
==> ("Fizz" = fizzbuzzer.Translate (x * 3))
[<Property>]
let ``A number not be divisable by 3 and multiplied by 5 will return Buzz`` (x:int) =
let fizzbuzzer = FizzBuzzer ()
(x % 3 <> 0)
==> ("Buzz" = fizzbuzzer.Translate (x * 5))
[<Property>]
let ``A number multiplied 15 will return FizzBuzz`` (x:int) =
let fizzbuzzer = FizzBuzzer ()
"FizzBuzz" = fizzbuzzer.Translate (x * 15)
[<Property>]
let ``A number not divisable by 3 or 5 will return self as string`` (x:int) =
let fizzbuzzer = FizzBuzzer ()
(x % 3 <> 0 && x % 5 <> 0)
==> (x.ToString() = fizzbuzzer.Translate x)
// more restrictive tests
[<Property>]
let ``A number not divisable by 5 but divisable by 3 will return Fizz`` (x:int) =
let fizzbuzzer = FizzBuzzer ()
(x % 5 <> 0 && x % 3 = 0)
==> ("Fizz" = fizzbuzzer.Translate x)
[<Property>]
let ``A number not divisable by 3 but divisable by 5 will return Buzz`` (x:int) =
let fizzbuzzer = FizzBuzzer ()
(x % 3 <> 0 && x % 5 = 0)
==> ("Buzz" = fizzbuzzer.Translate x)
// will fail with "Arguments exhausted" if not limited to around 50
[<Property(MaxTest=50)>]
let ``A number divisable by 15 will return FizzBuzz`` (x:int) =
let fizzbuzzer = FizzBuzzer ()
(x % 15 = 0)
==> ("FizzBuzz" = fizzbuzzer.Translate x)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment