This site works best in modern browsers. Looks like you're using an old one, you should upgrade if you can.

Improving Test Code Readability and Assert Failure Messages with Shouldly

Shouldly is an open source library that aims to improve the assert phase of tests; it does this in two ways. The first is offering a more “fluent like” syntax that for the most part leverages extension methods and obviates the need to keep remembering which parameter is the expected or actual as with regular Assert.Xxxx(1,2) methods. The second benefit manifests itself when tests fail; Shouldly outputs more readable, easily digestible test failure messages.

Failure Message Examples

The following are three failure messages from tests that don’t use Shouldly and instead use the assert methods bundled with the testing framework (NUnit, xUnit.net, etc):

  • “Expected: 9  But was:  5”
  • “Assert.NotNull() Failure”
  • “Not found: Monday In value:  List<String> ["Tuesday", "Wednesday", "Thursday"]”

In each of the preceding failure messages, there is not much helpful context in the failure message.

Compare the above to the following equivalent Shouldly failure messages:

  • “schedule.TotalHours should be 9 but was 5”
  • “schedule.Title should not be null or empty”
  • “schedule.Days should contain "Monday" but does not”

Notice the additional context in these failure messages. In each case here, Shouldly is telling us the name of the variable in the test code (“schedule”) and the name of the property/field being asserted (e.g. “Total Hours”).

Test Code Readability

For the preceding failure messages, the following test assert code is used (notice the use of the Shouldly extension methods):

  • schedule.TotalHours.ShouldBe(9);
  • schedule.Title.ShouldNotBeNullOrEmpty();
  • schedule.Days.ShouldContain("Monday");

In these examples there is no mistaking an actual value parameter for an expected value parameter and the test code reads more “fluently” as well.

To find out more about Shouldly check out the project on GitHub, install via NuGet, or checkout my Better Unit Test Assertions with Shouldly Pluralsight course.

FeatureToggle Version 3 Released

FeatureToggle logo image

Version 3 of my open source feature toggle library is now released to NuGet.

Version 3 introduces some breaking changes and new features.

Breaking Changes

  • The WPF value convertor package has been removed for version 3 as it’s trivial to implement a version in individual applications and reduce the maintenance overhead for the porject
  • Version 3 removes support for Windows Phone 8.0 (you can still use version 2.x if you need this support)

New Features

Platforms Support

In addition to .NET framework 4 full, version 3 also supports:

  • Windows Phone 8.1 Silverlight apps
  • Windows Universal Apps 8.1 (Store and Windows Phone 8.1 WinRT)
  • Windows Store 8.1 apps

Future versions will add support for Windows 10 apps.

New Toggle Types

The EnabledOnOrAfterAssemblyVersionWhereToggleIsDefinedToggle (a little verbose I know) allows a feature to become enabled once a specified assembly version number is reached. The assembly version used is that of the assembly inside which the toggle is defined, rather that the executing assembly. The configuration value for this toggle would be (for example) 0.0.2.1.

Future version will add support for comparing the executing assembly version.

New Decorators

A new type of feature that version 3 introduces is the idea of toggle decorators. These are classes that “wrap” one or more toggles and provide additional features.

The DefaultToEnabledOnErrorDecorator and the DefaultToDisabledOnErrorDecorator allows a default value to provided if there is an error evaluating the wrapped toggle value, for example with a configuration error. These decorators should be used with caution as your application may end up in an unknown state if you forget to configure something properly. In some cases you may want this behaviour rather than the application failing.

Assuming that a feature toggle called MyFeatureToggle has been defined, to use the decorator the following code would be used.

IFeatureToggle printFeatureThatDefaultsToDisabled = new DefaultToDisabledOnErrorDecorator( new MyFeatureToggle() );

bool isPrintEnabled = printFeatureThatDefaultsToDisabled.FeatureEnabled;

These decorators also allow you to specify an optional logging action that gets called if the wrapped toggle throws an exception:

new DefaultToDisabledOnErrorDecorator(wrappedToggle, ex => Console.WriteLine(ex.Message));

 

The CompositeAndDecorator allows multiple toggles to be wrapped, only if all these wrapped toggles are enabled will the decorator return true.

IFeatureToggle andToggle = new CompositeAndDecorator(new AnEnabledFeature(), new ADisabledFeature());

var isEnabled = andToggle.FeatureEnabled; // returns false

 

The final new decorator is the FixedTimeCacheDecorator. This allows a toggle that gets its value from a slow source (such as remote database, http, etc.) to have its value cached for a fixed period of time. To use this you specify the wrapped toggle and a TimeSpan.

IFeatureToggle cachedToggle = new FixedTimeCacheDecorator(cachedToggle, TimeSpan.FromSeconds(10));

 

Check out the release notes on GitHub. If you find any problems or bugs or want to suggest other features, please create an issue on GitHub.

xUnit.net 2 Cheat Sheet

To compliment the release of my Testing .NET Code with xUnit.net 2 Pluralsight course, I’ve updated my original xUnit.net cheat sheet.

xunit2 cheat sheet image

(To download just right-click, save-as)

Free eBook: Keeping Software Soft

I’ve decided to make my Keeping Software Soft eBook free (or feel free to pay whatever you’d like).

Keeping Software Soft eBook title page image

 

You can download now at http://keepingsoftwaresoft.com/

Happy Reading!

Clean C# eBook Published

The final version of my free Clean C# eBook has just been published.

Clean C# eBook Cover Image

 

You can download the book for free from http://cleancsharp.com/

The book contains the following chapters:

  • Comments
  • Naming Things
  • Methods
  • Structuring Programs for Readability
  • Errors and Exceptions
  • Visual Formatting
  • Cohesion and Coupling
  • Clean Tests
  • Building On Clean Code
  • about jason

    My Bio Photo

    Jason Roberts is a Journeyman Software Developer, Microsoft MVP, writer, Pluralsight author, open source contributor and Windows Phone & Windows 8 app author.

    He holds a Bachelor of Science in computing and is an amateur music producer and landscape photographer.

    MVP Logo

    Pluralsight Author Badge

    Sign up for the Don't Code Tired Newsletter

    Disclaimer
    The opinions expressed herein represent my personal opinions and do not represent my employer's views in any way.

    © Copyright 2015, Jason Roberts