Hook Execution Order in SpecFlow 2

SpecFlow hooks allow additional code to be executed before and after various stages of the test execution lifecycle, for example running additional setup code before each scenario executes.

If there are multiple of the same type of hook specified, by default the execution order of the hook methods is unspecified. For example the following code has three [BeforeStep] hook methods that could be executed in any order before every step of the scenario executes:

[BeforeStep]
public void BeforeHook1()
{
}

[BeforeStep]
public void BeforeHook2()
{
}

[BeforeStep]
public void BeforeHook3()
{
}

To ensure these hook methods are executed in a specified order, the hook attributes allow an optional order to be specified. When there are multiple of the same hook methods defined, the lowest order values execute before the higher order methods:

[BeforeStep(Order = 100)]
public void BeforeHook1()
{
}

[BeforeStep(Order = 200)]
public void BeforeHook2()
{
}

[BeforeStep(Order = 300)]
public void BeforeHook3()
{
}

The values of the Order property are arbitrary, you may use whatever values you wish, though it is sensible to allow some “wriggle room” for future additional steps by working in increments of 10 or 100 for example.

The following code illustrates another example where the execution order of hooks is important; the database should be reset first before test users are added:

[Binding]
public class Hooks
{
    [BeforeScenario(Order = 100)]
    public void ResetDatabase()
    {
    }

    [BeforeScenario(Order = 200)]
    public void AddTestUsersToDatabase()
    {
    }        
}

To see hook ordering in action, check out my Pluralsight course: Business Readable Automated Tests with SpecFlow 2.0.

New Pluralsight Course: Business Readable Automated Tests with SpecFlow 2.0

My newest Pluralsight course was just published. Business Readable Automated Tests with SpecFlow 2.0 teaches how to create tests that the business can read, understand, and contribute to. These “English-like” tests (other spoken languages are supported) can be executed by writing test code that is associated with the “English-like” steps. Because the tests sit alongside the source code, they can become living (executable) documentation for the system, as opposed to an out-of-date Word document somewhere on the network for example. Check out the course here.

The Joys of Silence

I recently took possession of new desktop PC. As a Pluralsight author one of the unique considerations when choosing a new machine was generated noise. After some research I settled on sourcing the computer from a UK company called QuietPC.com.

NoFan PC case from front

Initially when I started researching what to buy I had assumed that I would pay some performance penalty as I wanted a CPU with fan-less cooling and I didn’t want the additional complexity of something like water cooling.

As the following image shows, I was able to get a quad core Skylake (Core i7 6700K 4.0GHz) without requiring a fan:

Nofan CR-95C Pearl Black IcePipe 95W Fanless CPU Cooler

The humongous thing in the preceding image is a Nofan CR-95C Pearl Black IcePipe 95W Fanless CPU Cooler. This fan-less CPU cooler is based on thermal heatpipes that are able to transfer heat away from the processor, the heat then being dissipated by the huge surface area of the “fins”.

Nofan CR-95C Pearl Black IcePipe 95W Fanless CPU Cooler

The case itself is a Nofan CS-80 Fanless Computer Case coupled with a Nofan P-500A Silent 500W Fanless 80+ GOLD PSU. The case features a vent at the top of the case above the CPU cooler to aid in convection.

In use, the PC is completely silent, no fan noise or electrical hum – the only noise emitted is if you are used the optical drive.

Prior to this machine I was using and was very happy with a Lenovo laptop though under load the fan noise was becoming a little distracting – in all fairness it was an aging machine that had been an 8 hour a day workhorse for a few years.

It’s amazing that once you’ve experienced the joy of completely silent computing, going back to using machines with fans seems archaic. No doubt we’ll eventually have silent, high-performance, fan-less laptops – though the small form factor will present some hard thermal dissipation challenges.

Full hardware specs:

  • Nofan CS-80 Fanless Computer Case
  • Gigabyte GA-Z170XP-SLI LGA1151 ATX Motherboard
  • Intel 6th Gen Core i7 6700K 4.0GHz 91W HD 530 8MB Quad Core CPU
  • Corsair DDR4 Vengeance LPX 32GB (2x16GB) 2400MHz Memory Kit
  • Nofan CR-95C Pearl Black IcePipe 95W Fanless CPU Cooler
  • Nofan P-500A Silent 500W Fanless 80+ GOLD PSU
  • Samsung 950 PRO M.2 512GB NVMe SSD
  • Samsung 850 EVO 250GB 2.5in Solid State Drive
  • Pioneer DVR-221LBK DVD and CD Reader/re-writer
  • Gigabyte Dual Band Wireless-AC GC-WB867D-I Wi-Fi/Bluetooth Card
  • Gigabyte GC-TPM Trusted Platform Module

New Free eBook C# 6.0: What’s New Quick Start

C# 6 eBook Cover Image

The first chapters of my new free eBook have just been published.

The book will cover the new features added in C# 6.0 and provide a quick start to those new to version 6 or as a handy reference to those already using C# 6.0

New chapters are being added periodically and you can get the version now and get access to new chapters as they are published.

You can download the book for free or pay what you think it’s worth.

FeatureToggle v3.3 Released

FeatureToggle is an open source feature toggling library for .NET.

Version 3.3 was just released to NuGet and includes two minor new features as described below.

FallbackValueDecorator

The FallbackValueDecorator allows you to wrap (decorate) a primary toggle and specific a fallback toggle to be used if the primary toggle fails or is not configured.

new FallbackValueDecorator(new MyPrimaryToggle(), new MyFallbackToggle());

An optional overload allows the specifying of an Action<Exception> to be called if the primary toggle errors for example to perform some logging or alerting:

public FallbackValueDecorator(IFeatureToggle primaryToggle, IFeatureToggle fallbackToggle, Action<Exception> logAction = null)

CompositeOrDecorator

The CompositeOrDecorator allows the specification of two toggle instances, if either one of the toggles is enabled the decorator will return true:

new CompositeOrDecorator(new AnEnabledFeature(), new ADisabledFeature());


If you’re new to the concept of feature toggling or FeatureToggle check out my Pluralsight course Implementing Feature Toggles in .NET with FeatureToggle or the documentation.


Thanks to Craig Vermeer for the work investigating failing convention tests in VS2015 for this release.

New Pluralsight Course: Getting Started Building Windows Services with Topshelf

My newest Pluralsight course “Getting Started Building Windows Services with Topshelf” has just been released.

Topshelf is an open source library that makes it easier to develop, test, and install Windows Services.

If you’re new to Windows Services, the course starts by introducing how Windows Services work and some of their features such as automatic service recovery and the ability to run in the background as different users.

The course then goes on to cover how to create a Windows Service with Topshelf as well as additional techniques such as debugging, logging, pause and continue and the ability to send custom commands to running services.

Check out the course link or browse all my Pluralsight courses.

Testing That Your Public APIs Have Not Changed Unexpectedly with PublicApiGenerator and Approval Tests

We can write automated tests to cover various aspects of the code we write. We can write unit/integration tests that test that the code is producing the expected outcomes. We can use ConventionTests to ensure internal code quality, for example that classes following a specified naming convention and exists in the correct namespace. We may even add the ability to create a business readable tests using tools such as SpecFlow or BDDfy.

Another aspect that we might want to ensure doesn’t change unexpectedly is the public API that our code exposes to callers.

Using PublicApiGenerator to Generate a Report of our Public API

The first step of ensuring our public API hasn’t changed is to be able to capture the public API in a readable way. The PublicApiGenerator NuGet package (from Jake Ginnivan) gives us this ability.

Suppose we have the following class defined:

public class Calculator
{
    public Calculator()
    {
        CurrentValue = 0;
    }

    public int CurrentValue { get; private set; }

    public void Clear()
    {
        CurrentValue = 0;
    }

    public void Add(int number)
    {
        CurrentValue += number;
    }
}

Notice here that this code defines the public API that consumers of the Calculator class can use. It’s this public API that we want to test to ensure it doesn’t change unexpectedly.

We might start with some unit tests as shown in the following code:

public class CalculatorTests
{
    [Fact]
    public void ShouldHaveInitialValue()
    {
        var sut = new Calculator();

        Assert.Equal(0, sut.CurrentValue);
    }

    [Fact]
    public void ShouldAdd()
    {
        var sut = new Calculator();

        sut.Add(1);

        Assert.Equal(1, sut.CurrentValue);
    }
}

These tests help us ensure the code is doing the right thing but do not offer any protection against the public API changing. We can now add a new test that uses PublicApiGenerator to generate a string “report” detailing the public members of our API. The following test code shows this in use:

[Fact]
public void ShouldHaveCorrectPublicApi()
{
    var sut = new Calculator();

    // Get the assembly that we want to generate the public API report for
    Assembly calculatorAssembly = sut.GetType().Assembly;

    // Use PublicApiGenerator to generate the API report
    string apiString = PublicApiGenerator.PublicApiGenerator.GetPublicApi(calculatorAssembly);

    // TODO: assert API has not changed
}

If we debug this test and look at the content of the apiString variable we’d see the following text:

[assembly: System.Runtime.InteropServices.ComVisibleAttribute(false)]
[assembly: System.Runtime.InteropServices.GuidAttribute("c2dc3732-a4a5-4baa-b4df-90f40aad1c6a")]
[assembly: System.Runtime.Versioning.TargetFrameworkAttribute(".NETFramework,Version=v4.5.1", FrameworkDisplayName=".NET Framework 4.5.1")]

namespace Demo
{
    
    public class Calculator
    {
        public Calculator() { }
        public int CurrentValue { get; }
        public void Add(int number) { }
        public void Clear() { }
    }
}

Using Approval Tests to Assert the API Is Correct

Now in our test we have a string that represents the public API. We can combine PublicApiGenerator with the Approval Tests library to check that this API text doesn’t change.

First off we go and install the Approval Tests NuGet Package. We can then modify the test as shown below:

public class CalculatorApiTests
{
    [Fact]
    public void ShouldHaveCorrectPublicApi()
    {
        var sut = new Calculator();

        // Get the assembly that we want to generate the public API report for
        Assembly calculatorAssembly = sut.GetType().Assembly;

        // Use PublicApiGenerator to generate the API report
        string apiString = PublicApiGenerator.PublicApiGenerator.GetPublicApi(calculatorAssembly);

        // Use Approval Tests to verify the API hasn't changed
        Approvals.Verify(apiString);
    }
}

The first time we run this it will fail with a message such as “Failed Approval: Approval File "c:\…\Demo.Tests\CalculatorApiTests.ShouldHaveCorrectPublicApi.approved.txt" Not Found”. It will also generate a file called CalculatorApiTests.ShouldHaveCorrectPublicApi.received.txt. We can rename this to CalculatorApiTests.ShouldHaveCorrectPublicApi.approved.txt, run the test again and it will pass.

If we now modify the public API by changing a method signature (e.g. to public void Clear(int someParam)) and run the test again it will fail with a message such as “Received file c:\...\Demo.Tests\CalculatorApiTests.ShouldHaveCorrectPublicApi.received.txt does not match approved file c:\...\Demo.Tests\CalculatorApiTests.ShouldHaveCorrectPublicApi.approved.txt”.

Modifying the test and adding an Approval Tests reporter attribute ([UseReporter(typeof(DiffReporter))]) and running the test will now gives us a visual diff identifying the changes to the public API as shown in the following screenshot.

Approval Tests Diff Screenshot

To learn more about the features of Approval Tests, check out my Approval Tests for .NET Pluralsight course.

3 Tools for Choosing and Working with Color in Apps, Websites, and Print

When developing apps, websites, or even presentations for your team or management it can be difficult to come up with a working color scheme.

Below are three useful tools that can be of help.

Adobe Color CC (formerly Adobe Kuler)

Adobe Color CC Screenshot showing color wheel

Adobe Color CC is a classic color scheme designer based around the concept of the color wheel. You can choose a starting color and then one of the standard color schemes from color theory (complimentary, triadic, etc). This then gives you you the related colors based on the chosen color scheme.

For each color you can get the RGB, HEX, CMYK, LAB, and HSB values to use in whatever application your working on.

You can also explore a range of pre-built palettes created and shared by other users.

Paletton

paletton screenshot

Paletton is another tool based around the concept of the color wheel that offers a choice of color schemes. You can also use its “vision simulator” to simulate what the colors might look like to users with some kind of vision impairment.

The following image shows the same color sheme with no vision simulator (left) and protanopia – a form of color blindness (right).

paletton screenshot simulating color blindness

 

Multicolr

multicolr screenshot

Multicolr is an interesting tool that can help find images that match one or more colors. If you need to find images matching a set of colors this can be useful. To use Multicolr you start by selecting from one to five colors, in the preceding screenshot I have a chose a purple and white. The images come from flickr and you can select and image from the search results and view the original.

Winning in 2016

As the year 2015 starts its last slide into 2016, it’s the time of year that I start to think about what my 3 Wins are going to be for next year.

If you’re not familiar with the 3 Wins concept, it’s similar to goal setting but rather than focus on “what will I tick off my todo list” it’s more along the lines of “what will make me feel great, like I’ve accomplished something, like I’ve made progress…”. One way to help come up with three wins is to imagine how your future self will feel when you look back on the year and have accomplished all your 3 Wins.

It’s important to make your 3 Wins achievable, otherwise not achieving any of them could be disheartening and demotivating.

One technique to guide you, while being sounding very “managementy”, is the concept of SMART criteria.

SMART is an acronym that stands for:

  • Specific
  • Measurable
  • Attainable
  • Realistic
  • Time-related (or Time-bound)

Using SMART may help if you are struggling to create your own 3 Wins.

You might have 3 Wins for your work/career and you may also have 3 Wins for personal/health/family/etc. related things. Also you can use 3 Wins daily, weekly, monthly, quarterly, or at any scale you wish; you could even have decade or lifetime 3 Wins.