Scott Bellware posted a very interesting article around using C# 3.0 Extension Method to create the same effect as Ruby Mixin to extend existing objects with new methods.
Basically, what I’m talking about is the ability to add a method to an object within a specific context without accessing the sourcecode. For example, add a ToCamelCase() method to the string object in .NET.
This may sound like a bit of voodoo and for someone who’s only ever coded in an strongly typed language, it will definably look that way. But dynamic languages like Ruby and Small talk has always had this behavior.
“Enough rambling man, show us some code”
Here is some of Scott’s examples:
| NSpec in C# 2.0 | NSpec in C# 3.0 with NSpec.Extensions |
| Specify.That(actual).ShouldEqual(expected) | actual.ShouldEqual(expected) |
| Specify.That(actual).ShouldBeTheSameAs(expected) | actual.ShouldBeTheSameAs(expected) |
| Specify.That(actual).ShouldNotBeTheSameAs(expected) | actual.ShouldNotBeTheSameAs(expected) |
| Specify.That(value).ShouldBeTrue() | value.ShouldBeTrue() |
| Specify.That(value).ShouldBeFalse() | value.ShouldBeFalse() |
| Specify.ThrownBy(method) | method.ThrownBy() |
| Specify.That(actual).ShouldBeOfType(expectedType) | actual.ShouldBeOfType(expectedType) |
Here’s Scott’s example of an NSpec specification written in C# 3.0 that used the extension methods.
using NSpec.Framework;
// Import extension methods for NSpec
using NSpec.Extensions;
namespace Examples
{
[Context]
public class ExampleContext
{
[Specification]
public void A_string_should_equal_another_string_when_both_strings_have_the_same_value()
{
string s = "foo";
"foo".ShouldEqual(s);
}
}
}
This is really cool, because now you can write your expectations naturally on the object or property that you want to validate.
tags: bdd, c#3.0, rspec, tdd, testing
Currently listening to: Winamp *** 434. atb – drum n bass and beyond – prime





