BDD on Creatine
Thursday, March 12, 2009 9:46:14 AM (Mountain Standard Time, UTC-07:00)
In an attempt to further understand BDD, I chose to revise the code from my previous post after receiving some amazing advice from two people I regard highly (Scott & JP). I should state that this is my interpretation of that advice. This may or may not be the direction they were trying to guide me towards.
12 public class when_prompted_to_save_changes_to_the_project : concerns_for<SaveChangesView>
13 {
14 context c = () => { presenter = an<ISaveChangesPresenter>(); };
15
16 after_the_sut_has_been_created after = () =>
17 {
18 save_changes_window = sut;
19 save_changes_window.attach_to(presenter);
20 };
21
22 protected static ISaveChangesPresenter presenter;
23 protected static SaveChangesView save_changes_window;
24 }
25
26 public class when_the_save_button_is_pressed : when_prompted_to_save_changes_to_the_project
27 {
28 it should_save_the_current_project = () => presenter.was_told_to(x => x.save());
29
30 because b = () => save_changes_window.save_button.control_is(x => x.OnClick(new EventArgs()));
31 }
32
33 public class when_the_cancel_button_is_pressed : when_prompted_to_save_changes_to_the_project
34 {
35 it should_not_continue_processing_the_previous_action = () => presenter.was_told_to(x => x.cancel());
36
37 because b = () => save_changes_window.cancel_button.control_is(x => x.OnClick(new EventArgs()));
38 }
39
40 public class when_the_do_not_save_button_is_pressed : when_prompted_to_save_changes_to_the_project
41 {
42 it should_not_save_the_project = () => presenter.was_told_to(x => x.dont_save());
43
44 because b = () => save_changes_window.do_not_save_button.control_is(x => x.OnClick(new EventArgs()));
45 }
I hope this is slightly more soluble, then my previous post.
BDD on Steroids
Wednesday, March 11, 2009 1:40:59 PM (Mountain Standard Time, UTC-07:00)
In the last couple of weeks I had a chance to sprinkle some of JP's syntactic sugar, all over my projects. It's amazing how much more concise my units test have become. I've had a couple of issues where I was mocking out the behavior of some Win Forms controls, but for the most part it's been an awesome experience!
I just wanted to take a moment to say Thank you JP! I am enjoying using your BDD (on steroids) extensions. If you haven't already you need to check it out here. NOW!
Maaad, maaaad props Mr. JP!
10 public class behaves_like_save_changes_view_bound_to_presenter : concerns_for<SaveChangesView>
11 {
12 context c = () => { presenter = an<ISaveChangesPresenter>(); };
13
14 because b = () => sut.attach_to(presenter);
15
16 static protected ISaveChangesPresenter presenter;
17 }
18
19 public class when_the_save_button_is_clicked : behaves_like_save_changes_view_bound_to_presenter
20 {
21 it should_forward_the_call_to_the_presenter = () => presenter.was_told_to(x => x.save());
22
23 because b = () => EventTrigger.trigger_event<Events.ControlEvents>(
24 x => x.OnClick(new EventArgs()),
25 sut.ux_save_button
26 );
27 }
28
29 public class when_the_cancel_button_is_clicked : behaves_like_save_changes_view_bound_to_presenter
30 {
31 it should_forward_the_call_to_the_presenter = () => presenter.was_told_to(x => x.cancel());
32
33 because b = () => EventTrigger.trigger_event<Events.ControlEvents>(
34 x => x.OnClick(new EventArgs()),
35 sut.ux_cancel_button
36 );
37 }
38
39 public class when_the_do_not_save_button_is_clicked : behaves_like_save_changes_view_bound_to_presenter
40 {
41 it should_forward_the_call_to_the_presenter = () => presenter.was_told_to(x => x.dont_save());
42
43 because b = () => EventTrigger.trigger_event<Events.ControlEvents>(
44 x => x.OnClick(new EventArgs()),
45 sut.ux_do_not_save_button
46 );
47 }
Update: I posted the wrong link up top. here's the latest link.
I love milestones...
Thursday, November 06, 2008 11:20:23 AM (Mountain Standard Time, UTC-07:00)
I love being the guy to hit 1000 tests first... I guess I should check in first. doh!

Mocking Queryables
Tuesday, November 04, 2008 10:01:09 AM (Mountain Standard Time, UTC-07:00)
Recently, we've been mocking out IQueryable's as return values, which had led to setups that look like the following...
programs.setup_result_for(x => x.All()).Return(new List<IProgram> {active_program,inactive_program}.AsQueryable());
I just switched over to the following syntax... by creating an extension method.
programs.setup_result_for(x => x.All()).will_return(active_program,inactive_program);
The following are the extensions methods to make this work.
public static IMethodOptions<IEnumerable<R>> will_return<R>(this IMethodOptions<IEnumerable<R>> options,
params R[] items)
{
return options.Return(items);
}
public static IMethodOptions<IQueryable<R>> will_return<R>(this IMethodOptions<IQueryable<R>> options,
params R[] items)
{
return options.Return(new Query<R>(items));
}
and...
internal classQuery<T> : IQueryable<T>
{
private readonly IQueryable<T> query;
public Query(params T[] items)
{
query = items.AsQueryable();
}
public Expression Expression
{
get { return query.Expression; }
}
public Type ElementType
{
get { return query.ElementType; }
}
public IQueryProvider Provider
{
get { return query.Provider; }
}
public IEnumerator<T> GetEnumerator()
{
return query.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
Hope, this helps!
Droppin' Pennies on context specs...
Friday, August 15, 2008 8:07:20 AM (Mountain Standard Time, UTC-07:00)
First off I want to make it clear that I'm not a guru on the topic, but I do find it interesting. The topic of course is Context Based Specifications. I've seen an emergence in interest in writing context based specifications lately on the blogosphere. However, everyone seems to be advertising it slightly differently...
One of the things that our team tries to aim for is to keep technical language out of our specifications. They should be human readable sentences, not "Yoda" speak. This is crucial if we want non technical people to actually read our specs to make sure the code is inline with what the business is attempting to do. The goal, in our humble opinions, is to work closer towards the ubiquitous language. The benefit is that documentation is updated along with the code, because it is the code.
Something that reads..
when_the_account_controller_is_given_valid_arguments_on_the_register_account_action
Doesn't read as easy as:
when_registering_a_new_account
Another subtle change that our team made was to put the specs above establishing the context. In some cases it just seem to read better from top to bottom.
when_creating_a_new_account_for_a_user_with_a_valid_submission
- it_should_inform_the_user_that_the_account_was_created
- it_should_save_the_new_account_information
under_these_conditions
because_of
"It" being the system under test.
We don't always get it right, but by trying to drop the technical language we force ourselves to step away and think about the problem that we are ultimately trying to address.
Again... this is just my our 2 cents.
Parsing The Payload
Thursday, August 14, 2008 8:14:47 PM (Mountain Standard Time, UTC-07:00)
So this week we got to start working a brand spanking new MVC project. So far we're leveraging Castle Windsor, NHibernate, Fluent Nhibernate, and kind of running Linq to NHibernate. It's amazing how quickly you can get a project up and running in such a short amount of time. (BTW, Fluent NHibernate rocks!) When you're building off the trunk of these projects, it's almost like the contributors to all these great projects are extended members of the team. Thank you all!
Moving on... One of the things that are cool, but also slightly annoying, is how the MVC framework parses out items from the http payload to populate any input arguments on controller actions.
It's great how it just works, but it's a little annoying if it's under test and you have to add more fields, or remove fields from a form, then you have to go update the signature of the action then go update the test.... yada yada The changes just ripple down...
So one thing we tried out this week was to create a payload parser. What this guy does is take a DTO parse out the values for each of the properties on the DTO from the current requests payload and fill it. This makes it easy to package up the form parameters in a nicely packaged DTO and fire it off down to a service layer to do some work.
So instead of declaring an action method on a controller that looks like this, where the signature would have to change based on what fields are submitted on a form:
ViewResult register_new_account(string user_name, string first_name, string last_name)
We can write this...
public ViewResult register_new_account() {
var accountSubmissionDTO = parser.MapFromPayloadTo<AccountSubmissionDTO>();
var validationResult = task.Validate(accountSubmissionDTO);
if (validationResult.IsValid) {
task.Submit(accountSubmissionDTO);
return View("Success", accountSubmissionDTO);
}
return View("Index", validationResult.BrokenRules);
}
This better allows us to adhere to the OCP. If we need to include additional fields on the form, we can add them to the form as long as the control name is the same as the name of the property on the DTO that it will be bound to. The implementation of the payload parser is quite primitive for now, but at the moment it's all that we needed.
First up the specs... simple enough, for now!
public class when_parsing_the_values_from_the_current_request_to_populate_a_dto : context_spec<IPayloadParser>
{
[Test]
public void should_return_a_fully_populated_dto()
{
result.Name.should_be_equal_to("adam");
result.Age.should_be_equal_to(15);
result.Birthdate.should_be_equal_to(new DateTime(1982, 11, 25));
result.Id.should_be_equal_to(1);
}
protected override IPayloadParser UnderTheseConditions()
{
var current_request = Dependency<IWebRequest>();
var payload = new NameValueCollection();
payload["Name"] = "adam";
payload["Age"] = "15";
payload["Birthdate"] = new DateTime(1982, 11, 25).ToString();
payload["Id"] = "1";
current_request.setup_result_for(r => r.Payload).Return(payload);
return new PayloadParser(current_request);
}
protected override void BecauseOf()
{
result = sut.MapFromPayloadTo<SomeDTO>();
}
private SomeDTO result;
}
public class when_parsing_values_from_the_request_that_is_missing_values_for_properties_on_the_dto :
context_spec<IPayloadParser>
{
private AccountSubmissionDTO result;
[Test]
public void it_should_apply_the_default_values_for_the_missing_properties()
{
result.LastName.should_be_null();
result.EmailAddress.should_be_null();
}
protected override IPayloadParser UnderTheseConditions()
{
var current_request = Dependency<IWebRequest>();
var payload = new NameValueCollection();
payload["FirstName"] = "Joel";
current_request.setup_result_for(x => x.Payload).Return(payload);
return new PayloadParser(current_request);
}
protected override void BecauseOf()
{
result = sut.MapFromPayloadTo<AccountSubmissionDTO>();
}
}
public class SomeDTO
{
public long Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public DateTime Birthdate { get; set; }
}
The current implementation:
public interface IPayloadParser {
TypeToProduce MapFromPayloadTo<TypeToProduce>() where TypeToProduce : new();
}
public class PayloadParser : IPayloadParser {
private readonly IWebRequest current_request;
public PayloadParser(IWebRequest current_request) {
this.current_request = current_request;
}
public TypeToProduce MapFromPayloadTo<TypeToProduce>() where TypeToProduce : new() {
var dto = new TypeToProduce();
foreach (var propertyInfo in typeof (TypeToProduce).GetProperties()) {
var value = Convert.ChangeType(current_request.Payload[propertyInfo.Name], propertyInfo.PropertyType);
propertyInfo.SetValue(dto, value, null);
}
return dto;
}
}
Ambiguous Reference: Castle.Core.Interceptor.IInvocation
Friday, July 11, 2008 9:08:36 AM (Mountain Standard Time, UTC-07:00)
So yesterday I had this idea on how to run a background thread using an interceptor, but first I needed to Grok how the castle interceptors worked. I quickly ran into a snag, it looked something like this:
The problem is that the latest version of Rhino.Mocks hasn't internalized the castle dependencies. So the compiler doesn't know whether I'm referring to Castle.Core.Interceptor.IInvocation from the Castle.Core.dll or Castle.Core.Interceptor.IInvocation from Rhino.Mocks.dll.
I'm not sure why this is, so I did a little digging. And found this post... In one of the last comments someone else had this same issue...
I'm not really sure what this meant, so I decided to pull the source from the trunk. In the Rhino.Mocks project there's a file called "ilmerge.exclude" and in it was the interface that I was having trouble resolving (IInvocation). I removed it from the file, and rebuilt a release version. Seems to be working now.... I'm still not sure why this change was made... which makes me feel a bit uneasy.

Try it at your own discretion.
Holy Conditionals Batman...
Wednesday, July 09, 2008 7:17:32 PM (Mountain Standard Time, UTC-07:00)
In case you haven't you should read...
As a reminder, let's talk about a test smell described in the above mentioned book. It's called "Conditional Test Logic".
"Conditional Test Logic: A test contains code that may or may not be executed." xUnit Test Patterns
"A fully automated test is just code that verifies the behavior or other code. But if this code is complicated, how do we verify that it works properly?"
Warning bells should sound off in your head when you start to see looping or conditional constructs within a single unit test.
"Code that has only a single execution path always executes in exactly the same way. Code that has multiple execution paths presents much greater challenges and does not inspire as much confidence about its outcome."
For more information check this out...
Basically Ignore Logic... that could cause multiple execution paths within a single unit test.
Mocking Rhinos...
Sunday, July 06, 2008 8:07:42 PM (Mountain Standard Time, UTC-07:00)
I mean Grokking Rhino Mocks. My usage of Rhino Mocks has changed quite a bit since I first started using it a year ago, as well as the way I write tests.
First it was like this:
[TestFixture]
public class ConsoleTest {
private MockRepository mockery;
private IReportPresenter presenter;
[SetUp]
public void SetUp() {
mockery = new MockRepository();
presenter = mockery.CreateMock<IReportPresenter>();
}
[TearDown]
public void TearDown() {
mockery.VerifyAll();
}
[Test]
public void ShouldInitializeTheReportPresenter() {
var commandLineArguments = new[] {"blah"};
presenter.Initialize();
mockery.ReplayAll();
new Console(presenter).Execute(commandLineArguments);
}
}
Then it evolved to this...
[TestFixture]
public class ConsoleTest {
private MockRepository mockery;
private IReportPresenter presenter;
[SetUp]
public void SetUp() {
mockery = new MockRepository();
presenter = mockery.DynamicMock<IReportPresenter>();
}
[Test]
public void ShouldInitializeTheReportPresenter() {
var commandLineArguments = new[] {"blah"};
using (mockery.Record()) {
presenter.Initialize();
}
using (mockery.Playback()) {
CreateSUT().Execute(commandLineArguments);
}
}
private IConsole CreateSUT() {
return new Console(presenter);
}
}
Then for a short time I tried this...
[TestFixture]
public class when_giving_the_console_valid_arguments {
private IReportPresenter presenter;
[SetUp]
public void SetUp() {
presenter = MockRepository.GenerateMock<IReportPresenter>();
}
[Test]
public void should_initialize_the_report_presenter() {
var commandLineArguments = new[] {"blah"};
CreateSUT().Execute(commandLineArguments);
presenter.AssertWasCalled(p => p.Initialize());
}
private IConsole CreateSUT() {
return new Console(presenter);
}
}
Now I'm trying this...
[Concern(typeof (Console))]
public class when_the_console_is_given_valid_console_arguments : context_spec<IConsole> {
private string[] command_line_arguments;
private IReportPresenter presenter;
protected override IConsole UnderTheseConditions() {
command_line_arguments = new[] {"path", "testfixtureattributename"};
presenter = Dependency<IReportPresenter>();
return new Console(presenter);
}
protected override void BecauseOf() {
sut.Execute(command_line_arguments);
}
[Test]
public void should_initialize_the_report_presenter() {
presenter.should_have_been_asked_to(p => p.Initialize());
}
}
Now I'm generating reports from my tests specs using this. I wonder what's next...
Too Quick
Wednesday, May 21, 2008 3:39:52 PM (Mountain Standard Time, UTC-07:00)
Thank you Mr. Aaron, today we just grabbed the latest beta version of Rhino.Mocks and out test times significantly dropped....
Our times before the update were 450ish seconds to run all the unit tests and create the report:
Our times after are 100ish seconds:

The different flavors of tests
Friday, February 01, 2008 4:02:32 PM (Mountain Standard Time, UTC-07:00)
If you're going to practice any form of unit testing you need to learn about the different types of tests. I have yet to read XUnit Test Patterns, but I'm sure this will offer a great deal more detail then this post. Also, I'm anxiously awaiting "The Art Of Unit Testing"
Unit Tests
Unit tests are blocks of code that exercise very specific areas of a code base to ensure the it is meeting it's responsibility (NOT responsibilities in the plural sense. See Single Responsibility Principal). At it's core its asserting that a very specific result or behavior is met. Unit tests can be broken down into two types.
Black Box Testing (State)
The first is the traditional state based (black box) unit tests. These are unit tests that assert that components of the system exert a behavior that expected from the perspective of a client component. It cares less about the actual implementation of the component and more about the result. These types of tests tend to be easier to refactor and are a great way to start learning about test driven development or unit testing in general. The unit tests give you the confidence to go in to the trenches and make significant changes to the underlying implementation. This allows you to evolve a code base with confidence and precision. (And remember software development is an evolution. Using the same architecture and tools that you did from several years ago could indicate a smell.)
For example:
[Test]
public void Should_be_able_to_lease_a_slip() {
ICustomer customer = CreateSUT( );
ISlip slip = ObjectMother.Slip( );
ILeaseDuration duration = LeaseDurations.Monthly;
customer.Lease( slip, duration );
Assert.AreEqual( 1, ListFactory.From( customer.Leases( ) ).Count );
}
White Box Testing (Interaction)
This type of unit test is more focused on the interaction of components then the result. It's verifying expectations that components are working as expected with it's dependencies under different conditions. It's a way to simulate different environment conditions without actually having to exercise the component in that environment. The canonical example is to mock or stub out an interaction with a database or third party component.
It's called white box testing because it's like you can see clearly through the box to see what's going on inside. It might make more sense to refer to this as glass box testing.
For example:
[Test]
public void Should_leverage_task_to_retrieve_all_registered_boats_for_customer() {
long customerId = 23;
IList< BoatRegistrationDTO > boats = new List< BoatRegistrationDTO >( );
using ( _mockery.Record( ) ) {
SetupResult.For( _mockRequest.ParsePayloadFor( PayloadKeys.CustomerId ) ).Return( customerId );
Expect.Call( _mockTask.AllBoatsFor( customerId ) ).Return( boats );
}
using ( _mockery.Playback( ) ) {
CreateSUT( ).Initialize( );
}
}
Integration Test
Integration tests are tests that sweep across a system. They exercise the system from top down, to ensure that it is behaving as expected in a production like environment. This is a great place to weed out contracts that have not been implemented, and help to identify different environment scenarios that may need further unit testing. These tests actually hit the third party components and exercise the full system. These tests typically take a little longer depending on the environment conditions such as hitting a database.
There are frameworks available, such as Fit, that allow business analysts to define test criteria that can then exercise the system top down. The problem with some of these frameworks is that they can implicitly allow the BA to start designing how the system is implemented if taken as a literal design spec. I much prefer writing top down tests rather then implementing fit-like fixtures.
NUnit vs. MbUnit
Friday, October 26, 2007 10:30:21 PM (Mountain Standard Time, UTC-07:00)
Can't we all just get a long? A couple weeks ago I was asked why I preferred using MbUnit over NUnit... and i realized the question kind of stumped me. Did I choose MbUnit or did I just start using because everyone else is?
So why do I like MbUnit? I think the first reason is this... I'm glad the Unit Runner support for MbUnit is limited. I know there's a plugin some where that allowed you to debug your MbUnit unit tests in version 2.* of JetBrains Unit Test Runner. But since 3.0 came out it's been difficult to do, and I'm kind of glad!
My dependence on the debugger is becoming less and less. Admittedly, in the current project I seem to be running the debugger more because of my on going battle with Crystal Reports, but that's another story. I've found that since I started using MbUnit, I've spent less time using the debugger and more time developing new functionality. At first there was definitely a stunt in development when learning to work without the debugger, but I'm getting better on not relying on it, and i feel good about it.
I like the MbUnit reports... you can take your pick of text, html, xml or dox. The text report is great for getting quick feedback to see if your tests have passed or if you need to walk through the stack trace to find out where tests have blown up. (Just give me the line #) I haven't completed figured out what the "dox" report type is supposed to be used for or if it has any relationship to "doxygen", a great documentation generation tool I used to use during my days of C development (Thank you Mr. Mark!). But I like the report that it generates. It writes out the names of the tests so that they read almost like plain English. Here's an example:
- merchandise,should_ have_ 1 0_ percent_ sales_ tax
In the above example, "merchandise" was the name of the class and "should_ have_ 1 0_ percent_ sales_ tax" is the name of the test. Pretty clear and easy to read, it definitely describes the intent of each test nicely!
Combining the "/sr" (show report) switch with a command line build and a readable report makes for some quick development and quick feedback. It's awesome when you can bang out code, run a build quickly and get quick descriptive response to help you.
Next up... I'm liking the "RowTest" attribute. When it comes to triangulating tests against your subject under test, this attribute can come back handy. Take this for example:
[RowTest]
[Row( 12.49 )]
[Row( 0.85 )]
[Row( 9.75 )]
public void Should_Calculate_0_Percent_Tax_On_Item( double forPrice ) {
AssertAreEqual( 0, CalculateTax( forPrice, ZeroPercent ) );
}
Instead of having to write out 3 different tests, or jamming the 3 different assertions into a single test, I can make use of the "RowTest" attribute to ensure my subject is behaving as I expect it to. Pretty nice!
Next up, the "Rollback" attribute... when you decorate your test method with this little attribute it rolls back any changes made to a database. This comes in quite handy for an integration test against a database. Now you can also make use of the TransactionScope type as while and roll out your own base class for data access tests, but I like that this is baked right in to the unit testing framework. Although, I admit I have not spent much time using this feature yet.
One of the cool new features in the latest version of NUnit is a new "That" method, which allows you write more readable assertions. For example:
Assert.That(new Money(expected), Is.EqualTo(actual));
Right now it seems that integrating NUnit with other tools like CruiseControl is much easier and supported more, since it is the de-facto standard for unit test frameworks, but spending time trying to figure out how to get MbUnit to get along with others tools help you to get a better understanding of how each tool works and how they work with others.
Either way, I can't say I'm biased to either MbUnit or NUnit. I think they're both great unit testing frameworks and I'm glad that they're around and free to use.
Passionate Testing
Tuesday, June 05, 2007 3:53:27 PM (Mountain Standard Time, UTC-07:00)
I just read an excellent post on what I think a lot of developers go through when learning Test Driven Development. I have been for some time trying to convince my team to go TDD, well first I tried to get them to just write unit tests. TDD is somewhere over the horizon, but we'll get there!
One of the guys on my team was immediately fascinated by TDD, or maybe more so my love for it and began to give it a try. He went through those frustrating moments where you just want to say F-it, it's useless and causing me more head aches.
Soon it will one day make sense... I'm still learning to become a better test driven developer, and I know I am. I am already hooked, and very much dislike jumping onto existing projects that have zero unit tests. Debugging really is a waste of time... my 2 cents!