Thursday, November 5, 2015

Fluent Assertions FormatException when trying to include a Sitecore.Data.ID in your test failure messages

Recently, when using Fluent Assertions with my unit testing of a Sitecore project, I was attempting to display a friendly message when a block of code matched a Sitecore item that did not have a specific template ID.

My assertions looked like this:


Unfortunately, when running the test, I was getting an exception, but it was from FluentAssertions, rather than my code.

If I ran the test without attaching a debugger, my exception was "Input string was not in a correct format".


If I ran the test with a debugger attached, the exception was "Index (zero based) must be greater than or equal to zero and less than the size of the argument list."


Fortunately, when I attached the debugger, I could see that the message itself was fine, but Fluent Assertions was unable to handle it. Examining the value of message revealed the likely culprit.


String.Format uses curly braces to denote substitutions. Those curly braces are coming from the Sitecore.Data.ID implemention of ToString(), which looks like this:


After checking the documentation for the different format parameters for Guid.ToString(), we can see that passing the "B" argument to Guid.ToString() is generating the curly braces. Fortunately, the default ToString() method of Guid uses the "D" parameter, rather than the "B" parameter. This will output our Guid without curly braces.

With a very minor change to how we pass the ID to Fluent Asssertions, we can bypass ID.ToString() and get a message that will work with Fluent Assertions.


After making this change, my tests began outputting messages as expected.

No comments:

Post a Comment