Skip to content

Instantly share code, notes, and snippets.

@robfe
Created May 19, 2010 14:48
Show Gist options
  • Save robfe/406378 to your computer and use it in GitHub Desktop.
Save robfe/406378 to your computer and use it in GitHub Desktop.
Dynamic dispatch + printing of BDD steps
// Complementary to http://gist.github.com/406014. Just swap your BDD<T> base class for DBDD
// Also licensed under MSPL/FreeBSD/ISC
public abstract class DBDD
{
public readonly dynamic Given;
public readonly dynamic When;
public readonly dynamic Then;
public readonly dynamic And;
protected DBDD()
{
Given = new PrintingDispatcher("Given", this);
When = new PrintingDispatcher("When", this);
Then = new PrintingDispatcher("Then", this);
And = new PrintingDispatcher("And", this);
}
}
class PrintingDispatcher : DynamicObject
{
readonly string prefix;
readonly object source;
public PrintingDispatcher(string prefix, object source)
{
this.prefix = prefix;
this.source = source;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
MethodInfo methodInfo = source.GetType().GetMethod(binder.Name, BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
Debug.WriteLine("{0} {1} ({2})", prefix, binder.Name.Replace('_', ' '), String.Join(", ", args));
if (methodInfo != null)
{
methodInfo.Invoke(source, args);
}
else
{
const string format = @"You need a method like:
void {0}()
{{
throw new NotImplementedException();
}}";
throw new NotImplementedException(string.Format(format, binder.Name));
}
result = null;
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment