Skip to content

Instantly share code, notes, and snippets.

@philiplaureano
Created June 1, 2013 08:17
Show Gist options
  • Save philiplaureano/5689661 to your computer and use it in GitHub Desktop.
Save philiplaureano/5689661 to your computer and use it in GitHub Desktop.
Here's the simplest possible BDD framework I could conceive, using Nemerle. It uses FizzBuzz as a demonstration.
using Nemerle.Collections;
using Nemerle.Text;
using Nemerle.Utility;
using System;
using System.Collections.Generic;
using System.Console;
using System.Linq;
public class FizzBuzzer
{
public Print(number : uint) : string
{
mutable result = number.ToString();
when(number % 3 == 0 || number % 5 == 0)
{
if(number % 3== 0)
result = "Fizz";
else
result = "Buzz";
when(number % 3 == 0 && number % 5 == 0)
{
result = "FizzBuzz";
}
}
result;
}
public Foo() : void
{
}
}
public interface IThen[T]
{
Then(assertion : T -> void) : void;
Then(assertion : T -> bool) : void;
}
public interface IGivenContext[T]
{
When[TResult](action : T -> TResult) : IThen[TResult];
When(action : T -> void) : IThen[T];
}
public class TestCase[T] : IThen[T]
{
private _getResult : void -> T;
public this(getResult : void -> T)
{
_getResult = getResult;
}
public Then(assertion : T -> void) : void
{
def result = _getResult();
assertion(result);
}
public Then(assertion : T -> bool) : void
{
def result = _getResult();
NUnit.Framework.Assert.IsTrue(assertion(result));
}
}
public class GivenContext[T] : IGivenContext[T]
{
private _createContext : void -> T;
public this(createContext : void -> T)
{
_createContext = createContext;
}
public When[TResult](action : T -> TResult) : IThen[TResult]
{
def getResult() : TResult
{
def context = _createContext();
def result = action(context);
result;
}
TestCase.[TResult](getResult);
}
public When(action : T -> void) : IThen[T]
{
TestCase.[T](_createContext);
}
}
public static class Given
{
public A[T](createContext : void -> T) : GivenContext[T]
{
GivenContext(createContext);
}
}
module Program
{
Main() : void
{
def shouldPrintNumber(value : uint, text : string) : void
{
Given.A(FizzBuzzer).When(f => f.Print(value)).Then(result => result == text);
}
shouldPrintNumber(3, "Fizz");
shouldPrintNumber(5, "Buzz");
shouldPrintNumber(7,"7");
shouldPrintNumber(15,"FizzBuzz");
_ = ReadLine();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment