You probably know already that the Reactive Framework Extensions (Rx) is a new library on top of .NET 4.0 and Silverlight that allows developers to leverage the expressiveness and power of LINQ for .NET events. It brings an entirely new paradigm for doing event-driven apps, and therefore shines in WPF/Silverlight scenarios.
Read more about Rx at the team blog, the project home page and Matthew excelent blog series.
Even with the general availability of the bits for VS2010 beta2 at DevLabs, there's still quite a bit of work you need to do in order to leverage the extensions. Specifically, you need to turn your events into IObservables that can then use the Rx extensions for querying and subscribing. This is a lot of repetitive and boring code that can be easily automated.
That's precisely what this Clarius Labs provided extension does, enabling Reactive Framework Extensions for arbitrary assemblies, without writing any code. It basically traverses all public types in a given assembly (i.e. PresentationFramework.dll, for WPF) and generates a "Reactive" assembly for it (i.e. PresentationFramework.Reactive.dll) which contains the necessary extension methods for all public types that expose generic or custom delegate events that can be automatically converted to IObservables. With that in place, you can simply use the Reactive() extension method on your classes and access in a strong-typed fashion all events of that type as IObservables:

In order to get the extensions assembly generated, you simply right-click on a project or assembly reference, and select "Create Reactive Extensions":

and a new assembly will be generated and referenced automatically:

which will enable you to use LINQ operators and the new Observable APIs for all events exposed on all public types for the given assembly.
Matthew sample using our generator looks like:
var mouseMoves = from mm in mainCanvas.Reactive().MouseMove
let location = mm.EventArgs.GetPosition(mainCanvas)
select new { location.X, location.Y };
var mouseDiffs = mouseMoves
.Skip(1)
.Zip(mouseMoves, (l, r) => new { X1 = l.X, Y1 = l.Y, X2 = r.X, Y2 = r.Y });
var mouseDrag = from _ in mainCanvas.Reactive().MouseLeftButtonDown
from md in mouseDiffs.Until(
mainCanvas.Reactive().MouseLeftButtonUp)
select md;
Go to the Visual Studio Gallery and give it a try!
I'm sad to say it, but it is true. It slows you down. But not everytime, and not for everything. So let's be more specific on the cases where it DOES slow you down noticeably:
- Cowboy or Duct Tape Programming Mode: If you code all day like crazy in a "cowboy" or "duct tape" programming mode, then it WILL slow you down, significantly. In this mode, you're hacking together stuff that works by pure luck, you're only superficially and typically manually "testing" the thing, before calling it "done" and move on. Someone will come after some day when the customer complains about a bug, and figure out what to do. Not your problem though, for sure. For all you care about, you might even have another job by then. Your productivity kicks ass, you're the fastest guy in the team, and can get "complete" features to your boss in record time. Everyone (who hasn't worked with you long enough) thinks you're a genious, 'cause you can get something that works on the first shot. Brilliant!
It may also be just the way you are, and it's not that you don't care. It's just that your fingers fly and the itch to get the code done is SO strong that you just can't help it. Once I overheard an architect saying "I'm gonna tie your fingers with rubber bands!", hehe.
TDD WILL SLOW YOU DOWN, A **LOT**.
- Visual Studio Extensibility or Mobile Development: the red/green/refactor cycle is just so brutally slow that it's a real endurance test to try to keep doing TDD in many cases. Yes, you can isolate the IDE/Mobile environment, mock stuff here and there, but at the end of the day, the mock does not guarantee that things will actually work on the real thing. So you need to run tests on the actual environment more often than not. You'll spend a great deal of time trying to isolate slow areas, trying to write more code before you run just to avoid the slow turnaround (and then fixing multiple things in a single pass when multiple fail), etc. A total TDD-anti-climax for sure :(
TDD WILL SLOW YOU DOWN, **SIGNIFICANTLY**.
- Show Customer Value, Quickly: there are some cases where the domain you're tackling is not very well explored, or the customer doesn't have a very clear idea of what to expect, or doesn't even believe you can deliver something valuable or innovative at all. In these cases, it's much more important to have a lot of tangible value/features soon, than to have little but very robust and well designed via TDD.
TDD WILL SLOW YOU DOWN, AND YOU MAY NOT HAVE A PROJECT AT ALL SOONER THAN LATER
Of these, the first one is one that requires careful attention and mentoring. Being a speedy programmer certainly is a good quality and an important one to being great, I think. There are times when you just need to be bloody fast and get the job done quickly (third case). Such a developer is invaluable in an organization. But he must understand the constraints of the current project. Getting rock-solid, maintainable and well-designed code might be much more important than raw amount of features/code.
The second and third cases are just a matter of setting the right expectations, and understand how you're going to approach development. In either, you might skip TDD altogether, or do it only in more complicated areas only. Or you might just have what you can as integration tests only.
And yes, being pragmatic is also a very good quality to have. Shipping is indeed a feature.
Over the years I've come to realize that the one-fixture-per-class approach to unit testing just doesn't scale. As the amount of variations in state and interactions increases, that file starts becoming a big soup of "Should" methods that are increasingly difficult to traverse and find later on. Essentially, since every test is doing the first "A" in AAA (Arrange-Act-Assert) too, that means the context is also part of the test method.
You can only make a method so long and remain understandable at a glance: IfRepositoryContainsACustomerAndAddingANewOneWithSameIdButDifferentAliasThenThrowsInvalidArgumentException. So, a while ago at Clarius we started exploring some of the concepts behind BDD (Behavior Driven Development), Context/Specification, etc., while working on an internal project.
I was more than pleased with the compromise we made to accommodate our current tools, and to land in a place that is not totally alien for the regular "barebones"TDD guy. I'm convinced that changing paradigms just for this isn't probably worth it.
In my last post I hinted at one of the core values I see with TDD/unit testing: self-documenting code. Any kind of non-trivial code will involve a series of back and forth with the customer, numerous changes to a written spec (if you're lucky to have one) and its increasing and inevitable obsolescence. In most cases where I'm given enough freedom (i.e. the customer knows us well and trusts our development process and guaranteed quality), I usually get very few written specs, if any. A lot of details are just talked over standup (or IP), and many details are left for us to figure out. And that's fine: that's the reason you're the one with the keyboard writing code, and with the brains to make reasonable design choices if you understand the problem space well enough.
You could get picky with the customer and start asking for explicit definitions for everything. Tried that too, doesn't get you too far. In a short term, you're either out of the project 'cause you're too much of an overhead to an already busy person, or the customer gets even more exasperatingly vague and confusing as he tries hard to explain in detail something that doesn't even know yet for sure, while leaving crucial execution paths out, at which point you either quit politely, or go "don't worry, let me figure that out for you". Back to square zero.
The fact that the customer didn't know quite yet what he wanted, does certainly mean he doesn't want to know what he's getting. What you thought it was that he needed. So, you need to write whatever you write in such a way that it's easy to transform into a human-readable form that you can hand out to your customer.
So, without further ado, here's the way we write tests:
namespace Runtime.Workflow.JoinSpec
{
[TestClass]
public class GivenAJoinWithTwoPredecessorsAndOneSuccessor
{
// ctor builds up the context
[TestMethod]
public void WhenAPredecessorIsAvailable_ThenJoinIsBlocked()
{
// set predecesor state,
// verify the join has the given state
}
[TestMethod]
public void WhenBothPredecessorsAreFinished_ThenJoinIsFinished()
{
// set predecesor state
// verify the join changed state to Finished
}
}
}
How it works:
- The last part of the namespace becomes the logical grouping of the tests. This typically is the name of the class under test plus the "Spec" suffix.
- The test class starts with "Given" and the phrase that follows describes what's instantiated in the constructor and typically stored in fields for use by tests. The Given is the Arrange in AAA.
- Test methods have two parts: "When" and "Then", separated by an underscore.
- When: describes the action or state change that is caused in the context to perform the test. This is the Act in AAA. This is typically just one operation, but it could be more if changing the state/acting requires so.
- Then: the Assert in AAA. Typically just one Assert or mock Verify, but there could be more than one if verifying the state/interactions require so. But in either case, the Then should describe what you're asserting.
Key benefits of this approach:
- This is plain MSTest code. You could as well use xUnit, NUnit, etc. No new paradigms to learn, just some naming conventions.
- The only additional "overhead" is having a separate context (Given) class to group related tests (those tests that use the same setup).
- Having a convention in place for how to write tests has proven immensely valuable on its own. I can navigate our tests and not tell the difference on who wrote which tests.
- It triggers good practices about test complexity almost automatically: because context + tests have to make sense as an english phrase, sometimes you realize that a given test is testing too much (the test method becomes TOOOO long to write).
- It's trivial to write code that uses reflection to render this as a document
We use this as a guideline. There's no requirement that we have a context class. Sometimes, it's just not worth it because you're testing a very small unit. In this case, the *Spec becomes the class, such as:
namespace Runtime.Workflow
{
[TestClass]
public class FinalSpec
{
}
}
This is typically more the exception than the rule, though.
To render specs I quickly put together a query that uses reflection:
public class RenderSpecs
{
public void Render()
{
// Change and run with TestDriven.NET to get the specs for a given
// namespace:
Render("Runtime.Workflow", Console.Out);
}
public void RenderAllSpecs()
{
using (var stream = File.Open(@"..\..\Specs.txt", FileMode.Create))
using (var writer = new StreamWriter(stream))
{
Render("", writer);
}
}
private void Render(string withinNamespace, TextWriter output)
{
var specs = (from type in this.GetType().Assembly.GetTypes()
where type.Namespace != null && type.Namespace.StartsWith(withinNamespace) &&
type.GetCustomAttributes(true).OfType<TestClassAttribute>().Any()
from method in type.GetMethods()
where method.GetCustomAttributes(true).OfType<TestMethodAttribute>().Any() &&
method.Name.StartsWith("When")
orderby type.Namespace, type.Name
select new
{
Type = type,
Method = method,
//Phrase = method.Name,
When = ToPhrase(method.Name.Substring(0, method.Name.IndexOf('_'))),
Then = ToPhrase(method.Name.Substring(method.Name.IndexOf('_') + 1)),
})
.GroupBy(x => x.Type)
.OrderBy(x => x.Key.FullName)
.GroupBy(x => x.Key.Namespace);
foreach (var ns in specs)
{
output.WriteLine(new string('-', 50));
output.WriteLine(ToPhrase(ns.Key.Split('.').Last(), false));
foreach (var context in ns)
{
output.WriteLine(" " + ToPhrase(context.Key.Name));
foreach (var spec in context.OrderBy(spec => spec.When).ThenBy(spec => spec.Then))
{
output.WriteLine( " " + spec.When + ", " + spec.Then);
//Console.WriteLine("\t" + spec.Phrase);
}
}
}
}
private static string ToPhrase(string pascalCasedPhrase)
{
return ToPhrase(pascalCasedPhrase, true);
}
private static string ToPhrase(string pascalCasedPhrase, bool toLower)
{
var builder = new StringBuilder();
builder.Append(pascalCasedPhrase.First());
for (int i = 1; i < pascalCasedPhrase.Length; i++)
{
if (Char.IsUpper(pascalCasedPhrase[i]))
builder.Append(" ");
builder.Append(pascalCasedPhrase[i]);
}
var phrase = builder.ToString();
if (toLower)
{
phrase = phrase.ToLower(CultureInfo.CurrentCulture);
// Make only When and Then upper case
phrase = phrase.Replace("given", "Given").Replace("when", "When").Replace("then", "Then");
}
return phrase;
}
}
Note that this class is not a test class or test method. That's because we render on-demand. When I need to discuss or explain how a given area works, I'll go and render the specs first, email it and then meet. To run the Render method, I use TestDriven.NET which can run any method on any class (with a default constructor). I use it to run all tests too :), it's SOOOO much speedier than the VS runner...
Ayende wrote a controversial post titled I'm so smart I don't need TDD Even tests has got to justify themselves ;-). It's important to read it, because it reinforces many of the reasons why "regular developers" (i.e. NOT *you* if you're even reading blogs as you are) continue to see "us" as some kind of unreachable and infallible elite of "hero programmers" who will eventually show up (i.e. be hired for big bucks, which we surely do want :)) and save the day.
You see, Ayende appears to say that if you're smart enough, you'll just know what code to write, just like that. Ergo, if you don't know, maybe you're not that smart and hence you would need this technique for losers called Test Driven Design/Development.
That's not how it works, at least for me. Far from it. I've been doing TDD for years on several projects and with varying degrees of similarity. And I can tell you that even for those where I already had a very clear idea of an initial design, I always ended up with something (however slightly) different after doing it TDD-style. It consistently enriches my APIs by providing me a users point of view that an integration/scenario test would never give me.
Spikes
With regards to design uncertainty (which is what Ayende mentions as his only motivator for doing TDD), I usually take a different approach altogether: run a quick time-boxed spike (or several), to test a couple design choices quickly, without the "overhead" of doing it "right". These are throw-away spikes that you learn from. When I'm done with the learning, I go back to doing it with TDD, and it's almost guaranteed it will not look 100% like the spikes, and that it will be much more robust and user-friendly.
Documentation
A new appreciation I'm developing for TDD when done with certain consistent naming conventions (i.e. Given, When, Then style), is the ability to have a human readable and always up to date specification of what the various components do. Yes, this is not something you'll show your end users, but it IS something the developer or project lead coming after you can certainly learn from. Ayende assumes everyone will be equally smart as he is and immediately grasp his software designs, 'cause you know, there's only one way it could have been done right :P. In order to fix bugs and maintain non-trivial software, you need to know what individual components are doing.
Proof
I'll refer to one case of each situation where TDD provided value.
- Moq vs Rhino Mocks: he read the (useless IMO) literature on mocks vs stubs vs fakes, had apparently a clear idea of what to do, and came up with Rhino's awkward, user unfriendly and hard to learn API with a myriad of concepts and options, and a record-replay-driven API (ok, I'm sure it was not his original idea, but certainly it's his impl.) which two years ago seemed to him to stand at the core of mocking. Nowadays not only he learned what I've been saying all along, that "dynamic, strict, partial and stub... No one cares", but also is planning to remove the record / playback API too.
I'm pretty sure that if he had sat down with a blank project, two years ago, and rebuilt Rhino Mocks using TDD and a fresh mind, he would have ended with something very similar to Moq, way earlier, rather than seeming to be playing catch-up.
Moq on the other hand started from a blank slate, purely TDD-driven, with no preconceptions whatsoever on its API (other than the conviction that we just need one word, "mock"). I'm obviously biased, but users seem to love its simplicity too.
- Complex behavior: on a farily complex workflow-related implementation, I recently got asked what the behavior of a Join node was in our project. I could just run a test that does a very simple reflection-driven query and get the following answer to the project lead:
Join Spec
Given a join with two predecessors and one successor
When a predecessor is available, Then join is blocked
When a predecessor is blocked, Then join is blocked
When a predecessor is in progress, Then join is blocked
When a predecessor is unknown, Then join is blocked
When a successor state changes, Then join state does not change
When both predecessors are finished, Then join is finished
That is simply invaluable. Anyone coming later to the project only needs to read that to grasp an immediate understanding of the intended behavior. And it's isolated and unit-tested. How does the test code look like? Well, pretty much like your regular TDD-style, but with some naming conventions:
namespace JoinSpec
{
[TestClass]
public class GivenAJoinWithTwoPredecessorsAndOneSuccessor
{
// ctor builds up the context
[TestMethod]
public void WhenAPredecessorIsAvailable_ThenJoinIsBlocked()
{
// set predecesor state, and verify the join is with the given state
}
}
}
The new VSIX projects contain a manifest that is by default opened with a designer. No matter how many times you specify that you want to open it with the XML editor by default, VS will continue to open it with the designer.
The only way to force the change is to manually modify the .csproj as follows:
<ItemGroup>
<None Include="source.extension.vsixmanifest">
<SubType>DesignerCode</SubType>
</None>
</ItemGroup>
(on Beta1, the manifest file name would be just extension.vsixmanifest)
Last time I announced Linq to Mocks, some said Moq didn't actually have anything to do with Linq. Despite the heavy usage of lambda expressions and expression trees, the "q" in Linq is for "query" after all. And they were right, of course, but it was fun anyway, and the name is definitely cool IMO :).
But this time around, I'm happy to say that it's finally true. What the next version of Moq (early beta readily available now) allows you to express in a very declarative way essentially is:
from the universe of mocks, get me those that behave like this
(thanks Fernando Simonazzi for coming up with this phrase :))
Rather than procedurally defining how the mock will behave, its specification is part of the query:
ControllerContext controllerContext =
(from context in Mocks.Query<ControllerContext>()
where context.HttpContext.User.Identity.Name == "kzu" &&
context.HttpContext.Request.IsAuthenticated == true &&
context.HttpContext.Request.Url == new Uri("http://moq.me") &&
context.HttpContext.Response.ContentType == "application/xml"
select context)
.First();
A few things to notice:
- The query returns an infinite list of mocks that behave according to the specification/query. You typically get the first of such list.
- The resulting objects are of the actual mocked type, not Mock<T>, so there's no need to do controllerContext.Object anymore. The reasoning for that is that typically you would be able to fully setup the mock in the query, hence there'd be no need to get the Mock<T> back, unlike new Mock<T> where you do need to set it up.
- Fluent mocking happens automatically within the query. And even better, you're NOT limited to just property accesses. *Anything* that is a valid Setup on a mock can appear anywhere in the fluent mock traversal (i.e. context.HttpContext.GetSection("server") == configuration)
- You can have multiple mocks within the query and set them all up together.
- If you want to access these multiple mocks afterwards, you can just return all of them using an anonymous type projection (select new { Context = context, Configuration = configuration } ).
Here's a more comprehensive example of setting up two mocks at the same time:
ControllerContext controllerContext =
(from context in Mocks.Query<ControllerContext>()
from configuration in Mocks.Query<ServerSection>()
where context.HttpContext.User.Identity.Name == userName &&
context.HttpContext.Request.IsAuthenticated == true &&
context.HttpContext.Request.Url == new Uri("http://moq.me") &&
context.HttpContext.Response.ContentType == "application/xml" &&
context.HttpContext.GetSection("server") == configuration &&
configuration.Server.ServerUrl == new Uri("http://moq.me/api")
select context)
.First();
Finally, if you needed to access both the context as well as the configuration from the results of this query, you could do:
var mocks =
(from context in Mocks.Query<ControllerContext>()
from configuration in Mocks.Query<ServerSection>()
where context.HttpContext.User.Identity.Name == userName &&
context.HttpContext.Request.IsAuthenticated == true &&
context.HttpContext.Request.Url == new Uri("http://moq.me") &&
context.HttpContext.Response.ContentType == "application/xml" &&
context.HttpContext.GetSection("server") == configuration &&
configuration.Server.ServerUrl == new Uri("http://moq.me/api")
select new { Context = context, Configuration = configuration }))
.First();
MyController controller = new MyController { ControllerContext = mocks.Context };
// Do something with the configuration object...
ServerSection config = mocks.Configuration;
Next question would be how to setup exceptions to be thrown, and how to verify? You just use the existing Mock.Get functionality:
Mock.Get(controllerContext).Setup(...)
// or verify
Mock.Get(controllerContext).Verify(...);
Just for the sake of comparison, the equivalent "procedural" code to setup the same mock shown in the complete example above, you'd currently do:
var context = new Mock<ControllerContext>();
var configuration = new Mock<ServerSection>();
context.SetupGet(c => c.HttpContext.User.Identity.Name).Returns(userName);
context.SetupGet(c => c.HttpContext.Request.IsAuthenticated).Returns(true);
context.SetupGet(c => c.HttpContext.Request.Url).Returns(new Uri("http://moq/me"));
context.SetupGet(c => c.HttpContext.Response.ContentType).Returns("application/xml");
context.SetupGet(c => c.HttpContext.User.Identity.Name).Returns(userName);
context.Setup(c => c.HttpContext.GetSection("server")).Returns(configuration);
configuration.Setup(c => c.Server.ServerUrl).Returns(new Uri("http://moq.me/api"));
Yes, the query version has one more line of code, the .First() call. Yes, it's gonna be largely a matter of personal style and preference, just like many prefer invoking .Where(…) and .Select(…) instead of from…where…select.
Choice is good in this case, IMO.
There are many more features in this upcoming version of Moq. I'll try to blog about those too before/after we ship :). But this is my favorite!
Go get it!
Compile-time safety is always important, as it reduces the chances that a refactoring can break existing code that compiles successfully. This benefit took me previously to the path of using expression trees to achieve strong-typed reflection.
There is, however, an alternative that works on previous versions of .NET and doesn’t involve expression trees. It essentially involves creating a delegate of the target method, and using the delegate properties to get to the corresponding MethodInfo:
Action<string> writeLine = Console.WriteLine;
MethodInfo writeLineMethod = writeLine.Method;
Note that the code above is very explicit about which overload of the WriteLine method to pick: the one with a single string argument and a void return value. You can leverage Action and Func various overloads to represent pretty much any method invocation. Also, if those do not fit, you can still create your own delegate type. The benefit, clearly, is that you now can refactor the defining class or method and the change will be picked automatically.
The above example dealt with a static method call. Instance methods require an actual instance, but you can still use the technique to reflect over the method metadata What about instance methods? You certainly don't want to instantiate the target type just to do a more safe reflection over it, right? Well, because we're only retrieving a delegate to a method, but not actually executing it, passing a null is perfectly fine:
Func<object> cloneable = aCloneable.Clone;
MethodInfo cloneMethod = cloneable.Method;
How do you deal with generic classes, though?
public interface IFoo<T>
{
void Do();
}
In order to get the method, you need to have an actual concrete type of IFoo<T>, so you can just any type:
Action doMethod = aFooOfString((IFoo<string>)null).Do;
MethodInfo doMethodInfo = doMethod.Method;
The same trick applies to generic methods, but you need to get the generic method definition at the end:
public static class Factory
{
public static T Create<T>() { ... }
}
...
Func<string> createMethod = ((IFactory)null)Factory.Create<string>;
MethodInfo genericCreate = createMethod.Method.GetGenericMethodDefinition();
With these combined tricks, you don't need to (ab?)use expression trees for certain scenarios and it's backwards compatible with .NET 2.0.
If you have used more than one unit test framework (i.e. xUnit.NET, NUnit, MSTest/VSTS, etc.), chances are that you’ll miss features from one when using another.
In particular, MSTest/VSTS is lagging behind the crowd as it’s stuck in an NUnit circa 2002 (2.0) API for assertions and test attributes. This is what happens when you have a product that has to honor backwards compatibility even at the expense of usability and/or evolution of coding styles and API design.
Compare that with xUnit.NET, which had the luxury of starting from scratch just over a year ago, with all the accumulated learnings from NUnit and years of TDD work. The one assertion I missed the most from xUnit.NET was Throws:
Assert.Throws<ArgumentNullException>(() => service.Do(null));
Very explicit, highly precise check for an exception being thrown. MSTest, on the other hand, is still stuck in the (now even called a TDD anti-pattern, “The Secret Catcher”) attribute-based version:
[ExpectedException(typeof(ArgumentNullException))]
public void WhenDoReceivesNull_ThenThrowsArgumentNullException()
{
service.Do(null);
}
In this case, doesn’t look like a whole lot of difference, but if you have more than a couple lines of code in the test, chances are that the exception can be thrown by someone else in there and you would wrongly believe the test actually passed when it didn’t!
I also like xUnit.NET dropping the “Is” prefix on all assertions, which has always seemed redundant to me (i.e. Assert.NotNull vs Assert.IsNotNull).
Finally, with .NET 3.5 came along extension methods, essentially a way to infinitely extend any given interface as needs arise. Even xUnit.NET is lagging a bit there, but such is life for software: become partially obsolete on almost every rev of the underlying platform. Hence, leveraging now this open-ended extensibility mechanism in .NET seems like the obvious choice. And in the process, we would be able to bring in our beloved idioms from our favorite unit test framework.
Breeding New Life to MSTest APIs
In many projects you just don’t get to decide which test framework will be used. You’re given one. For many .NET developers working on Microsoft-only shops, that’s MSTest/VSTS and you have to live with it. Yes, things like TestDriven.NET can make it run fast (as it should natively) making it bearable. But you still have to use that old-looking API and there’s no easy way to extend it. Or is there?
As you probably know already, the key to extension methods is to have an actual instance of a type that we can use to hook the extension methods to. Hence, here is IAssertion:
public interface IAssertion
{
}
And a default implementation, which doesn’t need to provide any assertions, as we want all of them to be fully extensible and provided outside of these hook types:
public class Assertion : IAssertion
{
}
Now, let’s move on and define some basic assertions for IAssertion:
public static class BasicAssertions
{
public static void Equal<T>(this IAssertion assertion, T expected, T actual, string message = null, params object[] args)
{
Assert.AreEqual<T>(expected, actual, message, args);
}
... others
}
With that in place, we can easily enable this xUnit.NET style assertions quite easily:
[TestClass]
public class FooSpec
{
static readonly IAssertion Assert = new Assertion();
[Test]
public void WhenDo_ThenReturnsFoo()
{
var result = foo.Do();
Assert.Equal("foo", result);
}
}
Note how the test itself looks just like an xUnit.NET would. You can now get crazy and add whatever helper assertions you want via extension methods on IAssertion. Also, note how I’m mostly providing usability improvements on top of the underlying MSTest assertions, which is also nice. I’ve added the following two attributes to the assertion classes so that the debugging experience is nicer:
[DebuggerStepThrough]
[DebuggerNonUserCode]
How C# 4.0 Optional Simplify API Design
Current unit test frameworks provide multiple overloads for each assertion, so that you can provide an optional failure message to augment the default assertion failure message (i.e. “Account should be debited but it was not!”, rather than “Expected 0 but was 10”). Additionally, the message might even contain formatting arguments, such as "Should have been {0} but source account remained with a {1} balance", expected, account.Balance. With C# 4.0 optional parameters we can simplify what would be three overloads (one with no message, one with a fixed message, and one with a message plus formatting arguments) to just one:
public static void Equal<T>(this IAssertion assertion, T expected, T actual, string message = null, params object[] args)
In most cases where overloads just provide increasing amount of arguments that just enable overriding a default value, this new feature in C# 4.0 makes your code (the API but also the consuming code) much more explicit.
Get the assertions code from Clarius Labs.
Yes, what has beenreportedalready is indeed very true.
I bought 1984 a while back (from another publisher, though). Hadn’t started it yet, but all of a sudden, it was gone yesterday. Got a refund email from Amazon for it, a refund I never asked (and I never asked to the return the item either).
Just a couple hours ago, though, I got an explanation from Amazon:
We have recently refunded your purchase of Nineteen Eighty-Four (1984) by George Orwell. This book was added to our catalog using our self-service platform by a third-party who did not have the rights to the books. When we were notified of this by the rights holder, we removed the illegal copies from our systems and refunded previous customers.
We are working with the authorized rights holder to make this title available in our store very soon. We apologize for the inconvenience.
Amazon has made a couple not-too-smart choices lately. This one, and not allowing you to re-download your purchased DRM-free MP3 music.
I sincerely hope they fix both.
So Microsoft just shipped Silverlight 3.0. Outstanding achievement in its own right for a company that takes multi-year cycles for pretty much every product, if you ask me.
Silverlight is indeed a very cool technology. With the latest additions and especially the HD media capabilities, it’s already ahead of the crowd that it started “emulating”. I want to see Silverlight further expanded in the following two scenarios:
- Replacement for Media Center XML language: who wants to learn yet another UI markup language? Deprecate it, move to Silverlight-only.
- Embedded chipset with built-in support for an “Silverlight Embedded” profile
Replacement for Media Center
Currently, Media Center uses its own markup language and lacks tooling support that Silverlight/WPF enjoy (Blend/VisualStudio). It’s time to let it die and embrace Silverlight markup, even if that requires creating a “Silverlight Media Center” profile with a subset that must be supported by extenders.
Embedded Silverlight is the key
This is IMO where the bigger opportunity lies (and it also powers the previous one). Right now, we’re starting to see pervasive DivX support even in DVD players. The main reason is the availability of DivX certified chipsets that OEMs can leverage to build compelling and cheap products. Imagine what would it be if Microsoft partnered with chipmakers (would love to see an AMD/ATI partnership) to ship certified “Silverlight Embedded Profile” chips that supported VC1 playback as well as some markup subset for the UI. Given that VC-1 is already being adopted for Blue-ray content, it wouldn’t be too crazy to imagine a scenario where Silverlight-driven interactive content could be also provided in such disks.
With pervasive and cheap chipsets (maybe they could also honor VC-1 profiles to reduce processing power requirements for lighter scenarios), you could even imagine interactive content becoming part of picture frames, TVs, set-top boxes, DVD players, etc. etc.
If they take the idea further enough, you could even envision a .NET MicroFramework-powered certified chip that could even run some .NET code alongside pure XAML markup…
I’m telling you, Microsoft is on the verge of something BIG!
- Create a new Local Network with Virtual Network Manager (name it Hyper-V, for example)
- In the VHD, run msconfig.exe, in the Boot tab, click the Advanced options button, and select the Detect HAL option.
- Reboot the VM, reinstall the integration services and reboot again. Now you should get the new network adapter detected.
- Use ICS on the wi-fi network and select the local network Hyper-V as the one to share the connection with.
- To allow VPN access, you need to open a port (GRE) in the windows firewall as explained in http://help.wugnet.com/vista/VPN-server-configured-Generic-Routing-Encapsulatio-ftopict116489.html
The potential
You surely read quite a bit about Live Mesh. Oran Dennison has number of very technical and insightful posts on various aspects of the underlying platform.
Recently, we run an internal prototype to build an application on top of Live Mesh. I’m not talking about the kind of the typically showcased consumer-centric application where it’s all about sharing my personal photos, apps and videos with friends and family. I’m talking about a typical app for collaboration, involving group discussions (conversation-oriented like gmail), chat and shared calendar. Think about the aspects of Groove that are missing today from Live Mesh :).
The benefits of building an application on top of Live Mesh infrastructure are compelling:
- Built-in authentication, authorization and membership/account management via Live IDs
- Built-in transparent offline support (programming against the local Live Operating Environment is the same as for the cloud one)
- Automatic synchronization across nodes/users, with built-in conflict detection and preservation (which is different than conflict *resolution*, which is typically application-specific)
All these you’d have to build yourself if you were to develop an app requiring offline support. And compared to the other offerings such as Astoria Offline, Live Mesh certainly seems to be the one ahead of the crowd in terms of maturity.
With such an infrastructure in place, surely to be included sooner or later in every Windows box (with support for Mac and hopefully ported to Linux maybe via http://mesh4x.org?), it could become the obvious choice for pretty much any application. You’d be using Live Mesh as a general purpose store for your data, like a database. Imagine not having to think about offline, synchronization, authentication and authorization ever again! It almost sounds too good to be true.
In true Microsoft fashion, they have set to build a platform for all developers to leverage, not just a “file sync thinghy” like Dropbox, FolderShare or the myriad others. Being based on open standards (ATOM and FeedSync), it also allows others to join the platform and clears the doubts regarding vendor lock-in: you own the data, and it’s readily available for you to consume via a standard and documented API and format.
Social Applications
A somewhat less evident benefit of the platform is the ability to incorporate social networking capabilities right inside the application. Rather than going to a social network site/app to tell your friends which movies you liked, just rank the movie from within the player when you’re done watching it: all your friends using the same app can not only receive the rank but also know what you’re watching *right-now*.
Same principle applies to any application, where you could start ad-hoc collaboration with other users based on the current activity (i.e. we’re all filling out a form and you’re having a problem understanding something: you could just ask the other users who are working on the same form, or who have just completed it successfully), and even perform some of those together, such as browsing, authoring a document, etc. If you add the live mesh remote desktop functionality in the mix, you can imagine some very interesting possibilities.
So far, Live Mesh hasn’t introduced the concepts of networks and friends. Invites are for any Live ID user, regardless of whether they are in my contacts list or not. And it’s good that they haven’t mixed the two things at this point. We can share an application/Mesh object without being “friends” (we’re not in each other’s Messenger contact list). Over time, it would be interesting to allow the application developer to leverage something more social networking-oriented, such as inviting “my family” or “my coworkers” to share an application. I think this will eventually come to the platform, as the concept of groups in Live Messenger has silently evolved quite a bit, but they already have enough on their plate to work on for now.
The current shortcomings
The prototype didn’t end up very well, unfortunately. A number of limitations of the current (as of Apr 2009) Live Framework CTP prevent it from being used for general purpose client application development (I have no idea of mesh-enabled web application scenarios).
As a believer on the usefulness of reporting suggestions and bugs to Microsoft via Connect, each issue is followed by a link for you to vote if you think it’s important to get it fixed.
Invitations
First and foremost, there is a serious problem with the way invitations work: there is simply NO way for an application to accept invites, and currently the only way is to get an invitation *email* in your inbox with a link to your (web) live desktop site where you can accept the invitation. This is totally unacceptable for most applications. If we’re both using the same live mesh-powered application, and you invite me to share some data for it (in our prototype case, I could be invited to a discussion group), the obvious thing would be for me to receive a notification *in the application* that I’ve been invited, and be able to accept it right from there. Alternatively, I could receive the invitation via the Live Mesh notifier tray icon, and accept it from there too. Either way would work, but the current approach is simply impractical. Moreover, the UI says you’ve been invited to a “Live Mesh Folder”, which is totally misleading as accepting the invitation takes you to the live mesh desktop UI where nothing new seems to have happened after accepting (‘cause there’s no new folder to show!). I believe this to be a drawback of focusing too much on the file sharing “sample app” (I still believe Microsoft should open source it and use it as a showcase of what great things you can do on top of Live Mesh, but it should still be just another regular citizen in the mesh, with no more privileges as my own apps).
Generic Data Store
In order for Live Mesh to succeed as an application platform that you rely on to replace your typical database, it has to provide the same capabilities we’ve come to expect from them, and efficient and flexible querying is a critical part of it. Currently, even though Live Mesh allows you to store custom data (i.e. your entities, albeit in a rather XML-ugly way) in the entries, rich querying over that data is impossible. It’s even impossible to query over custom attributes or elements at the item level if you decide to go with the low-level Syndication API way.
Beyond just XPath-like querying, I think Live Mesh as a generic store should provide a LINQ provider like Astoria does, so that you can work with your data at the domain/entity level, and let the infrastructure handle the serialization and storage (i.e. partition entities across feeds, ensure referential integrity, etc.). I doubt anyone wants to be writing queries over ATOM feeds once you’ve become addicted to LINQ querying.
Online/Offline Inconsistencies
Even though API-wise it doesn’t matter whether you’re talking to the local LOE (Live Operating Environment) or the cloud LOE, the operations you can do vary in somewhat unpredictable (and certainly undocumented) ways. For example, you cannot create a MeshObject (the elemental unit of authorization and sharing) if you’re offline, or invite users, etc.
In order to enable true offline apps, at the bare minimum the current inconsistencies need to be addressed.
It’s also unclear how authentication works (or doesn’t) when you’re offline, or how you can achieve peer-to-peer synchronization in the absence of internet connectivity.
Conclusions
I remain excited by Live Mesh possibilities. I think it will be a game changer, and it will play an increasingly important role as a general purpose application platform. It won’t achieve all that overnight, and it will take a couple of revs to get the platform there.
I wouldn’t advise you to take a hard dependency on Live Mesh right-away. The Live Framework CTP is ahead of the public Live Mesh beta
From the point of view of the user of the container, he doesn't have to do anything at all. He just creates classes as usual:
public class EditCustomersPresenter
{
public EditCustomersPresenter(IEditCustomersView view, ICustomerRepository repository)
{
this.view = view;
this.repository = repository;
view.Presenter = this;
}
...
}
Container configuration is done through lambdas that specify which object to construct for the registered type. For the view used by this presenter (an EditCustomersView form), it would look like:
var container = new Container();
container.Register<IEditCustomersView>(
c => new EditCustomersView());
In this sense, you can think of Funq as a glorified dictionary of delegates to instantiate objects (it does a bit more than that, though). In the above case, the class we're constructing doesn't need any dependencies. If it did, such as the presenter above, you can use the "c" argument to the lambda, which is the container itself, which you can use to express that you'll need to resolve the dependencies to pass on:
container.Register(
c => new EditCustomersPresenter(
c.Resolve<IEditCustomersView>(),
c.Resolve<ICustomerRepository>()));
Note that because this is a lambda/delegate, it won't actually be executed until the presenter is needed. Moreover, note how the type to register can be omitted if it matches the created object type (i.e. you don't want to register the presenter as an interface).
Because this is configuration, you can also pass configuration data on your registrations:
container.Register<ICustomerRepository>(
c => new CustomerRepository("[CONNECTION STRING TO DB / AppSetting / etc]"));
Moreover, the object itself can expose properties that affect its behavior, which can also be initialized at this point using C# 3 object initializer syntax:
container.Register<ICustomerRepository>(
c => new CustomerRepository("...") { IsAudited = true });
More lambda "magic" makes it possible to arbitrarily initialize the object when it's constructed, by using the InitializedBy fluent method:
container
.Register<ICustomerRepository>(
c => new MemoryCustomerRepository())
.InitializedBy((c, r) =>
{
// Initialize with some fake data.
r.Create(new Customer { FirstName = "Joe", LastName = "Doe" });
r.Create(new Customer { FirstName = "Sarah", LastName = "Smith" });
r.Create(new Customer { FirstName = "Mary", LastName = "Brown" });
});
The InitializedBy method receives a lambda with two arguments: the first is again the container, in case we need to further resolve dependencies, and the second is the instance created by the first delegate (at the time it was needed), typed to the registration type (ICustomerRepository in this case, or the constructed instance type if you omitted it) passed on so that you can call methods, set properties, etc. on it.
Lazy resolve
Let's say a service needs to be able to create/resolve a dependency on-demand. Typically, you'd create a factory for that, and have the factory instantiate the object through the container. Funq provides built-in support for this via factory functions as a built-in concept.
If you had a controller that instantiated use cases as needed, you wouldn't want to create all the possible use case classes up-front. So let's say you have a registered use case class:
container.Register<IUseCase>("AddCustomer", c => new AddCustomerUseCase());
Note that instances can be named so that you can register many under the same interface.
The controller class would need to run this use case at some point. It would have a constructor dependency not the actual instance, but on a resolver delegate to it:
public class CustomersController
{
public CustomersController(Func<IUseCase> addCustomerResolver, ...)
{
...
}
public void AddCustomer()
{
// invoke the function, which would create the use case as registered.
IUseCase useCase = addCustomerResolver();
useCase.Run();
}
}
You'd register the controller slightly different, by lazy resolving the use case dependency
container.Register(
c => new CustomersController(
c.LazyResolve<IUseCase>("AddCustomer"))
The LazyResolve method works (and provides same overloads) just like the Resolve, but it returns Func delegates instead, so that the actual invocation to Resolve is delayed until you execute the delegate. This is very useful in many scenarios, and avoids many one-line factories.
Passing constructor arguments
Another common scenario we wanted to support without sacrificing performance was to allow passing constructor arguments to these registered "factories". Let's say you have a Queue object that needs the queue name:
If you have the following queue class:
public class Queue : IQueue
{
public Queue (string queueName)
{
...
}
}
You'd register it like so:
container.Register<IQueue, string>(
(c, name) => new Queue(name));
Note how you specify in addition to the service type, the type of the arguments that it requires. In order to resolve it, you must therefore pass a string for the invocation:
var queueOut = container.Resolve<IQueue, string>("outgoing");
This would allow you to configure something like a notifications service with two queues with different names:
public class NotificationService : INotificationService
{
public NotificationService(IQueue input, IQueue output)
{
...
}
And its corresponding registration would be:
container.Register<INotificationService>(
c => new NotificationService(
c.Resolve<IQueue, string>("in"),
c.Resolve<IQueue, string>("out")
);
This also works for lazy resolution, so if the service creates the queues on-demand, it could be defined as follows:
public class NotificationService : INotificationService
{
public NotificationService(Func<IQueue, string> queueResolver)
{
...
}
public void Reply(string message, ...)
{
using (var queue = queueResolver("out"))
queue.Enqueue(message);
}
Note that the service invokes the resolver passing the queue name. Registration would be slightly different now:
container.Register<INotificationService>(
c => new NotificationService(c.LazyResolve<IQueue, string>())
);
Passing arguments can also be done at registration time for dependencies. Imagine you introduce a IQueueFactory service that must receive a queue name in its constructor so that its caller can create multiple instances of the same queue object as needed, without knowing the queue name at all. A notification service would use such a factory as follows:
IQueueFactory factory;
public NotificationService(IQueueFactory factory)
{
this.factory = factory;
}
public void Send(string text)
{
using (var queue = factory.CreateQueue())
{
queue.Enqueue(text);
}
}
The service doesn't know which particular queue it's going to send the message to. And (for whatever reason) it needs to create a new queue whenever it needs it. The registration for such an object, would simply be:
container.Register<IQueueFactory, string>(
(c, name) => new QueueFactory(name));
Note how the registration overload we're using specifies that in addition to the service type, we'll need a string argument to construct the object. Now it's time to register the notification service, which (say) we have two of: input and output notifications
container.Register("outgoing",
c => new NotificationService(c.Resolve<IQueueFactory, string>("out-queue")));
container.Register("incoming",
c => new NotificationService(c.Resolve<IQueueFactory, string>("in-queue")));
What's happening here is that we're registering the same service twice with different names, and resolving the queue factory dependency passing the desired queue name that will be received by its implementation. This way, we have externalized the dependency on this knowledge from the notification service.
The same effect (of "fixing" a lambda parameter to a given value) can be achieved by just currying the function returned from LazyResolve :)
If you follow my blog, you probably heard about Funq, and maybe you even watched the screencasts I did about it while developing it (yeah, I'm missing a bunch of new ones!).
When we started working on a rev for the original Mobile Client Software Factory v1 for patterns & practices, we had a list of top-priority issues and feature requests expressed by the community and the advisory board. Very high on the list was *removal* of the Composite UI Application Block (CAB) from the blocks, as its performance impact was too great for mobile apps.
Despite all my efforts to make CAB more performant (including compile-time codegen a-la sgen of the injection policies), I just couldn't make it fly. It was simply not designed for a constrained execution environment where things like allocated bytes and JIT compilation DOES matter.
Yet, we didn't want to just rip-off CAB and leave nothing to replace it. Designing an application in a loosely coupled way and enabling testability are important goals that we wanted to encourage in the mobile world. So I decided to start from scratch on the simplest possible DI container we could give mobile developers that could add sufficient value to their architectures without compromising application cold boot speed or general runtime performance.
The culmination of that effort is a very simple container (I claim anyone can crack open the source code and understand it quite easily ;)) that outperforms every other DI container on the market by orders of magnitude. I named the new Mobile Application Blocks (MAB) DI framework ContainerModel. p&p already has a desktop/silverlight offering in the space with Unity, so with their authorization, I forked (but keep 100% in sync) the project into Funq, which provides the desktop and silverlight binaries and source. So, MAB ContainerModel == Funq. It may be that the latter adds features that only apply to the desktop and/or silverlight (i.e. ASP.NET MVC and WCF integration, etc.), but the core will always remain in sync.
The performance results for the CF version are:
Here you can see how bad ObjectBuilder v1 (the backbone of CAB) was, even at a generous (estimated average) 7x performance gain via compile-time codegen, resulting in a 133x overhead! (without the obgen compile-time tool, it would be ~900x :S).
In comparison, the new ContainerModel is a modest 12x slower than no DI at all, and still orders of magnitude faster than a quick port to CF of both Autofac and Unity.
On the desktop, numbers are also equally encouraging:
This shows only the top 3 performing containers, as including others such as Windsor ruins the graph (it's 6x slower than Autofac, about 80x slower than Funq).
As I said, key performance counters you typically don't measure on the desktop are of critical importance on the CF. So I developed the container while carefully watching the impact on those. Here are the results and comparison:
As you can see, Unity does significantly better than the original ObjectBuilder, but it was still not enough for CF. The new ContainerModel overhead is barely noticeable across all areas, with consistently low impact.
To be honest, the comparison on the CF is unfair to the other frameworks, because none of them were designed nor optimized for use on mobile devices. I just ported enough of the code to get them to compile and run.
Over the next few posts, I'll explain more about its design and features. Stay tunned!
There are few groups within Microsoft that are as open and so quick to deliver as patterns & practices. When you give them feedback or request features, chances are you'll see them implemented within months, rather than years (if they get enough support of the rest of the community!).
It's now time to engage in shaping EntLib 5.0! From Grigori's blog:
At this point, we would like to invite you to select and prioritize candidate features/stories you care about. Please review them carefully along with the associated effort estimates and cast your votes. Do remember to stay within the budget (100 points). Here's the link to the online survey.
I wish the format for the survey was more user friendly, but don't let that stop you from voting!
If you're doing any kind of WPF development, you probably read at least some of the links in this entry on WPF Patterns.
One common theme across all variants of the ViewModel pattern is that it always has to implement the INotifyPropertyChanged interface, which is the core interface driving the whole data-binding infrastructure in both WinForms and WPF. Implementing this interface is quite boring and repetitive, more so if you're using C# 3.5 automatic properties:
public class Customer
{
public string FirstName { get; set; }
public Address Address { get; set; }
// other properties
}
We need now to add the event raising call to every setter, but in order to do that, we have to convert the automatic properties into regular ones, with the corresponding backing field, etc.:
public class Customer : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
Address _address;
string _firstName;
public string FirstName
{
get { return _firstName; }
set { _firstName = value; this.RaisePropertyChanged("FirstName"); }
}
public Address Address
{
get { return _address; }
set { _address = value; this.RaisePropertyChanged("Address"); }
}
// other properties
private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
Pretty standard stuff. But wait, that Address property seems like it should also implement INotifyPropertyChanged! What's more, seems like we should also be tracking changes in nested/child objects and raising the change from the parent property too! (i.e. someone changes Address.City, the Customer.Address should be considered changed).
This quickly adds to the tedium, not to mention how error-prone all this is (just one copy/paste where you forget to change the property name) and also how annoying it gets when you need to refactor the code with all those strings.
Well, quite some time ago (back in 2007) we released an early version of a custom tool that would generate all this repetitive stuff for you. This tool has evolved quite a bit as we used it in various projects, and now we have a revamped release, which has been renamed to ViewModel Tool. The tool supports VS2008 on both C# and VB projects.
The tool can also generate (opt-in) ISupportInitialize, ISupportInitializeNotification and IChangeTracking implementations.
Enjoy and please report any issues you may find via the Issue Tracker (select ViewModel Tool as the component). Go get it!
Objective of the method: determine whether the given EnvDTE code class contains the given GeneratedCodeAttribute:
"old" foreach/if approach:
private bool IsPresentationModel(CodeClass2 baseClass)
{
foreach (CodeClass2 pc in baseClass.PartialClasses)
{
foreach (CodeAttribute2 attr in pc.Attributes)
{
if (attr.FullName == typeof(GeneratedCodeAttribute).FullName &&
attr.Value.Contains(ThisAssembly.Title))
{
return true;
}
}
}
foreach (CodeAttribute2 attr in baseClass.Attributes)
{
if (attr.FullName == typeof(GeneratedCodeAttribute).FullName &&
attr.Value.Contains(ThisAssembly.Title))
{
return true;
}
}
return false;
}
Note that most collections in the EnvDTE code model are not IEnumerable<T>. Here's the linq-ified version:
private bool IsPresentationModel(CodeClass2 baseClass)
{
return baseClass.PartialClasses
.OfType<CodeClass2>()
.Select(cc => cc.Attributes)
.SelectMany(ce => ce.OfType<CodeAttribute2>())
.Concat(baseClass.Attributes.OfType<CodeAttribute2>())
.Where(attr =>
attr.FullName == typeof(GeneratedCodeAttribute).FullName &&
attr.Value.Contains(ThisAssembly.Title))
.Any();
}
The SelectMany invocation is needed to flatten the list of attributes from all partial classes :)
Update: Changed Count() to Any() which is generally more optimal, as I only care about knowing whether there's at least one such attribute, regardless of how many.
Over the years doing TDD, I'm getting increasingly concerned about the value my test fixtures are bringing to the table in terms of documenting features and expected behavior.
So far, I followed the typical pattern in TDD of creating one class (fixture) per object under test: if I have DirectoryService, I create DirectoryServiceFixture. Inside the fixture (and for the past couple years now), I've been pushing teams I work with to stick to a convention where every test method is prefixed with the word "Should": this seems to be at least a bit aligned with BDD, in the sense that it causes your mind to shift into explaining what behavior you're exercising.
But sometimes a sentence of that format doesn't make a lot of sense, and I started to get sloppy with it. And I'm at the point where I desperately need a better way of thinking about my tests, as right now I can't really look at a test run result and figure out what it is that the system does really, which are the scenarios and the contexts.
I like it that BDD does away with the "Test" word, which in TDD is hopelessly misleading, as mentioned by Scott Bellware, and evidenced in Joel's awful misunderstanding of what it's all about. Starting a presentation or discussion on TDD invariably derives into questions about the value of testing, the role of QA, and so on. I'm tired of that, as it has NOTHING to do with that.
Beware that (in my opinion) there's nothing terrible new or revolutionary about BDD. I believe its value lies in being a form of neuro-linguistic programming (as mentioned in the NSpec page) which leads you to a different way of thinking and expressing the behavior you code. It's mostly a way to structure and name the code you already write if you're doing TDD, so that it has more value as a documentation tool and a communication tool with users and business stakeholders. There are, however, some BDD libraries that go to the extreme of making the code look absolutely alien. You don't have to use them in order to apply the principles, though.
So, during my exploration of BDD, I found the following resources quite useful:
- BDD Intro by Dave Astel: the easiest to read and understand, and to map to current TDD practices, without convoluting the practice with too much language noise (unlike Dan North's).
- Beyond TDD: BDD, by Dave Astel too. A good introductory video conference to BDD and what are some core principles, although I do not agree on the emphasis he puts in "stay away of state testing", but other than that, pretty good. It makes me realize that something like Moq can support this style very well.
- Introducing BDD, by Dan North, who coined the term. Straightforward, easy to understand, and to the point.
- Some alternative ways of reading context/specification: a *very* helpful and dispassionate comparison of the various alternative/conventions for doing BDD. I'm kind of leaning towards the AAA syntax as it's more familiar to what I'm doing already.
- Behavior-Driven Development: in Scott's typical style, a rather long way to explain it all (still quite useful especially for newcomers). I don't like the Context/Because convention, though. It doesn't flow very well IMO.
I'm still learning about it. Will try to apply it in a concrete project and keep you posted.
Got to get my blog on a decent engine so that you can post comments! Sorry :(