NBehave, Dates and value conversions

Some of the guys at my work are starting to get into NBehave in a big way and today asked me an interesting question around how NBehave captures parameter values out of scenarios.  Consider these methods:

[Given("a user has logged on as $username")}
public void SetupUser(string username) { }

[When("the user asks for all blog posts since $fromdate")
public void LoadBlogPostsSince(DateTime fromdate) { }

[Then("they should see $num blog posts")]
public void CheckNumberOfBlogPosts(int num) { }

[BTW please refer to my previous post for an explanation of how methods like this can be invoked by NBehave, if you aren’t familiar with it]

Now you’ll notice that each of these methods capture a parameter value from the scenario.  So if we were to invoke these methods against the following:

Given a user has logged on as Bob
When the user asks for all blog posts since 24/05/2010
Then they should see 15 blog posts

Then the captured parameter values (on my system!) would be “Bob”, “24-May-2010” and “15”.  This is all quite simple, except for the fact that our method parameters are strongly typed and hence some conversion is required.  My colleague was specifically asking about the handling of dates and how NBehave parses it.

NBehave actually calls System.Convert.ChangeType to perform the conversion.  This is a pretty general function which relies heavily on the IConvertible interface to do the hard work.  Curiously, I didn’t actually know that this method existed until I looked into the NBehave code!  But anyway, this method relies on the current thread culture for date parsing.  And this means that the above scenario will not run for a thread running under en-US (since “24/05/2010” is not a valid date in that culture) but will run and yield the expected results on a thread running under en-GB.

June 17 2010
blog comments powered by Disqus