jimmy keen

on .NET, C# and unit testing

Introduction to F# unit testing for C# developers

July 16, 2016 | tags: f# c# unit-testing

I recently picked up F# as a tool for one of my pet projects. After getting familiar with syntax and tools, natural next step was to write few unit tests. How did it go?

C# background

When writing tests in C# I would use the following libraries:

This is more or less state of the art in modern C# development. Of course you can replace any library with its alternative. However, it will not be a breakthrough but rather a cosmetic change. The big picture remains the same.

It is possible to have nearly identical setup in F# with a single library – FsUnit (save from mocking framework but we will get to that later).

F# unit test

Currently I use Visual Studio 2015 Community, which is just enough for F# development on Windows box. Assuming we have our IDE sorted:

  1. Create F# Library project (no, you don’t need any script file in there)
  2. Add FsUnit package (this will also install NUnit 3 dependency)
  3. Add NUnit3TestAdapter package (it is important to have this otherwise VS will not detect your tests)

And write simple test:

module JimmyKeen.Paterns.UnitTests

open FsUnit
open JimmyKeen.Patterns.Candles
open NUnit.Framework

[<Test>]
let ``Candles overlap when parts of their bodies occupy same price range``() =
    let candle1 = Candle(20161010, 10.0M, 12.0M, 9.0M, 11.0M, 1000, 0)
    let candle2 = Candle(20161011, 10.5M, 11.5M, 10.0M, 11.5M, 1000, 0)
    overlapRatio candle1 candle2 |> should equal 0.5M

Notice the double-backtick identifier which allows us to be very verbose with test names. Other than that, this is very similar to what our C# test would look like.

Wait, did you forget about FakeItEasy?

You might have noticed that F# setup is missing mocking framework. Why is that?

Let’s ask different question – why do you need mocking framework in first place? Because you have some dependency that should behave different during production and test run. And existing language features do not make changing this behavior easy. It is possible, but requires lot of boilerplate code. Mocking framework does this mundane work for us.

Now in C#, primarily object-oriented language, dependencies are other objects which in most cases will be a class instance. In F# we want to deal with functions. Functions, which will depend on other functions. Think about C# class which has a dependency to a Func<T>, rather than other class:

public class RiskCalculator
{
    private Func<int, int> ageCategoryComputer;

    public RiskCalculator(Func<int, int> ageCategoryComputer)
    {
        this.ageCategoryComputer = ageCategoryComputer;
    }

    // ...
}

You do not need any special framework to mock such dependency. In test you would simply create lambda expression.

In F# it is always like that. As a result, usage of mocking frameworks is very limited (but not completely gone). You can, and perhaps should design your code so that mocks are not required. If you want to hear more about this approach I recommend watching “Look, no mocks!” presentation by Mark Seemann.

Where to go from here

I believe that starting with FsUnit and Visual Studio is the easy-transition path for C# developer. Once you get familiar with that approach, there are other ways to develop with F#. You don’t need Visual Studio. There are few more, novel options for tooling libraries. We’ll take a look at that in next blog post.

Using Git with Powershell on Windows

November 10, 2015 | tags: git windows powershell posh-git

This will be a quick guide on how to set up Powershell with Git on Windows.

Essentials

  1. Powershell
  2. Git for Windows
  3. Git credentials store

Download and install files above. Make sure Git bin directory is added to your PATH environmental variable. Credentials store are not really required but I’m pretty sure you do not want to type your login details with every push or pull, right?

Aliases

Just as with any console application, Git offers a way to streamline your work with aliases. Rather than typing

> git add -A

> git commit -m "Added config file"

You can simply type

> git c "Added config file"

This of course goes further than that considering we have Powershell at our disposal. For example, you can easily create alias like this:

> git config --global alias.logby "!f() { git log --author='`$1'; }; f"

> git logby Jimmy

We create f function and execute it straight away. You can read more about this approach at “Git alias with parameters”. When setting such alias from powershell itself, make sure to escape $-variables with ` (grave accent symbol), otherwise powershell will try to insert variables which are not there.

You can see some more aliases here.

The Posh

A neat little extension offering git commands completion and making your Powershell look like this:

posh-git powershell highlighting

Posh-git can be installed from powershell:

> (new-object Net.WebClient).DownloadString("http://psget.net/GetPsGet.ps1") | iex

> Install-Module posh-git

If your powershell compains that your execution policy is restricted, make sure to un-restrict it with:

> Set-ExecutionPolicy RemoteSigned

It’s great we can see current branch name. It’s also great that we can see whether there were any modifications. But I’m not a huge fan of having all the details of changed files, untracked, stashed and so forth. I would rather have this:

posh-git powershell simplified highlighting

A simple indicator telling me what branch I am on and what’s the status (* - pending changes, - synced with origin, - ahead of origin).

Behavior described above can be achieved if we modify posh-git code, namely GitPrompt.ps1 file. You can find this file location in one of your powershell modules directories (check $env:PSModulePath variable). You can use the files from my repository:

And that’s it. Enjoy your brand new Git + Powershell experience!

Refactoring unit tests for readability

June 07, 2015 | tags: c# unit-testing refactoring

Any fool can write code that a computer can understand. Good programmers write code that humans can understand. - Martin Fowler, 2008

The code you produce will be read. The “brillant” class you have just written and forgotten might sit idle for many months. Then it breaks. It’s Friday evening and hotfix is needed right now because crucial invoicing procedure is generating weird, negative invoices for no reason!

Your poor colleague, Joe, is assigned to this dreaded task only to find your class. With elaborate algorithms solving simple tasks, because optimization1. With rarely used LINQ method. With neat, little code trick. With bit of “hackerish” list operations you had then learnt from some cool blog.

Sure, the implementation worked great. Unfortunately, not for Joe. He most likely understands nothing of it. Not because he has brain freeze or is slightly slower. It is because you had produced unreadable, unmaintainable ball of mud.

Why readability matters

Joe would have been just fine if you had kept your solution simple. Saved cool tricks and hacks for your pet projects at home. Didn’t optimize prematurely. Instead, focused on solving problem at hand and making sure your code is as simple to follow as possible. It is invaluable in situations like the one described above.

Now… how do you improve readability of your code? To discover that, we’ll take a look at the ExportTaskScheduler class, solving one specific business requirement – scheduling export:

public void ScheduleExportTask()
{
    var futureTask = new FutureTask
    {
        TargetIdentity = "ExportTask",
        CommandType = typeof(ExportCommand),
        PreparationDate = timeService.Now().AddSeconds(10),
    };
    var launcher = new Launcher
    {
        LaunchTime = timeService.Now().AddMinutes(10),
    };

    futureTaskScheduler.ScheduleFutureTask(futureTask, launcher);
}

That’s all there is. This code is fairly simple and readable. Method has well-defined, single responsibility (schedules export2) and is only few lines long. Anybody reading it should be able to tell what’s going on almost immediately. Readability goal has been achieved. Or… has it?

Let’s take a look at its unit test:

[Test]
public void TestScheduleFutureExportTask()
{
    var taskScheduler = A.Fake<IFutureTaskScheduler>();
    var timeService = A.Fake<ITimeService>();
    var scheduler = new ExportTaskScheduler(taskScheduler, timeService);
    A.CallTo(() => timeService.Now()).Returns(10.May(2015).At(13, 33));

    scheduler.ScheduleExportTask();

    A.CallTo(() => taskScheduler.ScheduleFutureTask(
            A<FutureTask>._, A<Launcher>._))
        .WhenArgumentsMatch(args =>
        {
            var futureTask = args.Get<FutureTask>(0);
            futureTask.CommandType.Should().Be(typeof(ExportCommand));
            futureTask.TargetIdentity.Should().Be("ExportTask");
            futureTask.PreparationDate.Should().Be(10.May(2015).At(13, 33, 10));

            var launcher = args.Get<Launcher>(1);
            launcher.LaunchTime.Should().Be(10.May(2015).At(13, 43));

            return true;
        })
        .MustHaveHappened(Repeated.Exactly.Once);
}

This code is certainly not as readable as implementation one. Why is that so? Unfortunately, unit tests are often treated as “second class citizen”, a code where regular practices and patterns don’t apply. This is a mistake. You will often find test methods without descriptive name, spanning multiple screen, weird mocks usage, cryptic variables naming – all developer’s careless attitude visible through code. Just as if unit test was some sort of different, less important code. It is not. It is production-level one, just as any other.

Without further due, let’s go over the issues one by one.

1. Test method name

The TestScheduleFutureExportTask tells us nothing. This is bad because method name is first thing we will see (especially when test fails) and it’s the name which should give us brief overview of testing scenario (so that we get to know what we are dealing with quickly). Using one of the popular naming conventions we arrive at something closer to ScheduleExportTask_SchedulesCorrectTask_10MinutesFromNow.

2. Variables names

Since we deal with two schedulers, high level one (scheduling business process) – ExportTaskScheduler, and low level one (scheduling code commands described by some objects) – FutureTaskScheduler, we should pay extra attention to how these two variables are named. The current choice (taskScheduler and scheduler) is rather poor as it is harder to discover which is which. Rule of thumb is to keep the variables names long, without any “smart” abbreviations. In the long run, exportTaskScheduler is an immediate tell, while scheduler, taskScheduler, tScheduler or exTskSchd are not.

3. Dealing with time

We use FluentAssertions syntax to neatly create DateTime instances but truth to be told, the exact value is irrelevant in this test. We need some point in time because we assert how other values relate to this given point (task is scheduled 10 minutes from now). We are better of with hiding exact value, for example in static field:

private static readonly DateTime Now = 10.May(2015).At(13, 33);

Then, our asserts are much more verbose:

launcher.LaunchTime.Should().Be(Now.AddMinutes(10));

4. Asserting values

Since this is the rare test of verifying whether some other component was called (with correct parameters) and we are already doing asserts inside WhenArgumentsMatch the simplicity has taken a hit. What we could do is extract the assertions to separate methods. Our test now looks like this:

[Test]
public void ScheduleExportTask_SchedulesCorrectTask_10MinutesFromNow()
{
  var futureTaskScheduler = A.Fake<IFutureTaskScheduler>();
  var timeService = A.Fake<ITimeService>();
  var exportTaskScheduler = new ExportTaskScheduler(futureTaskScheduler,
      timeService);
  A.CallTo(() => timeService.Now()).Returns(Now);

  exportTaskScheduler.ScheduleExportTask();

  A.CallTo(() => futureTaskScheduler.ScheduleFutureTask(
          A<FutureTask>._, A<Launcher>._))
      .WhenArgumentsMatch(args =>
          IsFutureTaskCreatedCorrectly(args) &&
          IsLauncherStarting10MinutesFromNow(args))
      .MustHaveHappened(Repeated.Exactly.Once);
}

It is good as it is but there are few more things we could do. They might not be as beneficial in this simple case but as the number of test cases grows, they will make a difference.

5. Extracting instances creation

For any test case, the way system/class under test instance is created is most likely irrelevant. What matters is easy access to such instance and clear, intuitive name (and we’ve already dealt with that). To put that noise away, we can move such preparation steps elsewhere. For example, to NUnit’s SetUp method where each instance is created and stored in class field:

[SetUp]
public void InitializeComponents()
{
    futureTaskScheduler = A.Fake<IFutureTaskScheduler>();
    timeService = A.Fake<ITimeService>();
    exportTaskScheduler = new ExportTaskScheduler(futureTaskScheduler,
        timeService);
}

This way, the arrange part tells that current time is this and this, which is the only relevant information.

6. Verbose arrange

…which could be improved further. How? By wrapping it in a more verbose method, like:

SetCurrentTimeTo(Now);
SetCurrentTimeToNow();
CurrentTimeIs(Now);

The more test cases we got, the more beneficial such verbose arranges get. Similar thing can be done to assert part but since it will be different for different tests, there is little gain (we won’t be able to reuse such verbose assert). The final version of unit test might look like this:

[Test]
public void ScheduleExportTask_SchedulesCorrectTask_10MinutesFromNow()
{
  SetCurrentTimeTo(Now);

  exportTaskScheduler.ScheduleExportTask();

  A.CallTo(() => futureTaskScheduler.ScheduleFutureTask(
          A<FutureTask>._, A<Launcher>._))
      .WhenArgumentsMatch(args =>
          IsFutureTaskCreatedCorrectly(args) &&
          IsLauncherStarting10MinutesFromNow(args))
      .MustHaveHappened(Repeated.Exactly.Once);
}

Conclusion

Readability is important. Simple, easy to understand code is important. Somebody is going to read our work one day, maybe in a big hurry. We don’t want to make their work harder.

To learn more about practices similar to the ones presented in this post, I recommend Robert C. Martin book, Clean Code, and his training videos based on the book (these can be found online).

  1. Premature, of course.

  2. One might argue that there’s hidden responsibility in creation of objects (FutureTask and Launcher). However, these are DTO-types and we should look at them just as we would look at string, int and similar types.