Book Image

Testing with F#

By : Mikael Lundin
Book Image

Testing with F#

By: Mikael Lundin

Overview of this book

Table of Contents (17 chapters)
Testing with F#
About the Author
About the Reviewers


When I started out with unit testing in 2007, I made every imaginable mistake there is. I didn't understand how to isolate my tests from database calls. I didn't understand how to structure my tests. I had no idea what constituted a good test and what should be tested. It was a train wreck, and even if my test suite was pretty much useless, I still found I had gained a lot of knowledge of the system while trying to test it. So, for the next project, I gave it another go.

Once again, in my second project, I failed at writing unit tests. They where brittle, unmaintainable, and quite useless as they would only run under conditions that where reproducible solely on my developer machine. But even if the test suite was crap, the project itself was a success and the code produced was considered to be of very high-quality.

So, I went at it again and again and again, every time coming up with a slightly better end result, until I got to a point where the test suite was a major deliverable of the project, and an enabler for maintenance. However, it took me a long time to get there.

I had been teaching and preaching test-driven development for years, until I began to notice that people around me were doing it, too. I no longer had to justify TDD to people around me, and testing would now be a natural part of any project, and not just something I did on the side. This was splendid, indeed! Mission accomplished!

In 2009, I found out about the F# language from Microsoft Research, and it got my attention. I decided to learn it, and started to hack away during my evenings and weekends to get to the bottom of functional programming. After a while, I felt sure enough to start bringing it into clients' projects. I began with only small snippets at the start, but after a while, the snippets got bigger and bigger, and before anyone knew what was going on, we were implementing services in F#.

For me, test-driven development has been an enabler for quality. It is what enhances the quality in a given project by setting up requirements on the code. The code needs to expose its inner parts in a manner that can be tested in isolation. This leads to good object-oriented design and separation of concerns.

However, at the same time, I had a few worries that the test suite made too large impact on the system design. Why isn't it that we design systems that are testable by default, and why do we need tests to enforce this design thinking?

Functional programming has truly been an eye-opener for me. There is something funny about object-oriented programming I didn't realize before I invested in F# fully. Why is it that I can't create a class in the system without setting up a dependency injection framework? Why do we have all these classes that are cohesive enough that they only do one thing, but that one thing is so abstract that the name of the class is more confusing than informative? Why does every class in the system have an interface identical to the class implementation?

The answer to these questions is that test-driven development has forced these frameworks and patterns onto object-oriented design in order to work together in harmony, but in reality, you end up with a lot of ceremonial code that does very little.

Functional programming is the answer to this question; anyone care to object?

If we stop thinking about systems as interconnected objects and instead see them as functions passing data around, we make our design so much easier. We can skip the dependency injection framework because we don't need to manage an object dependency graph. We do not need interfaces because we can describe functions by their signature. Instead, we can solely focus on the input and what the desired output will be, and from this, we will derive our tests.

While my colleagues struggle with their cloud in the castle abstractions, I produce code that is short, concise, and completely covered. This is the best way to evangelize something better. We do not need to sell functional programming. It sells itself.

Yet, here I have written a book about producing quality code with functional programming and testing. This is a starting point for anyone who is familiar with object-oriented programming and wants to learn about the alternatives that may bring about a more qualitative life as a professional programmer.

I wanted to write this book in order to spread the word and show my peers what huge value they're missing out on by trying to produce value with C# and object orientation alone. My intention is to express the lost love I have found for programming after being stuck in large enterprise code bases where every change would have a ripple of side effects. I want to put this book in the hand of every developer I meet who is asking himself, "How could I do better?"

Your managers will love you for writing less code and getting done at a much faster rate of speed. Your clients will love you for producing code with less bugs. And you will love going to work to deliver code with higher value and less ceremonial waste.

Understanding functional programming and test-driven development are the key points in advancing your career and securing your knowledge base for the inevitable future.

What this book covers

Chapter 1, The Practice of Test Automation, gives an overview of the current field of test automation and an introduction to set the terminology. This chapter will give you a good sense of why test automation is needed.

Chapter 2, Writing Testable Code with Functional Programming, dives into functional concepts in order to write code that promotes testability. This chapter provides you with the introduction to functional constructs that will be used while writing unit tests.

Chapter 3, Setting Up Your Test Environment, acts as a tutorial on setting up your test environment in order for you to start testing, and is focused on tools such as NUnit, xUnit, and the built-in MSTest framework. It also provides a short guide for build scripts and continuous integration with F#.

Chapter 4, Unit Testing, lets you deep dive into unit testing with F# and using functional programming to drive unit tests and testability. It provides examples on how to test in isolation and stubbing, as well as dealing with dependencies and mock away databases.

Chapter 5, Integration Testing, explains how to write good integration tests in F# and what to think about when writing integration tests. We deal with the differences in integration testing with databases to those in external web services.

Chapter 6, Functional Testing, uses tools such as TickSpec in which you can write executable specifications in order to test on a higher abstraction level, which is closer to what the end user will experience.

Chapter 7, The Controversy of Test Automation, brings the reader up to date on what is being said about test automation in the community.

Chapter 8, Testing in an Agile Context, explains how to bring testing into a team and apply it in an agile process. This chapter provides arguments to convince your manager about the benefits test-driven development.

Chapter 9, Test Smells, informs you that just like code smells are an indication of an underlying problem in your design, there are also test smells that indicate there is an underlying problem with your tests.

Chapter 10, The Ten Commandments of Test Automation, covers 10 dos and don'ts of test automation, which comes from 8 years of test-driven development knowledge.

Chapter 11, Property-based Testing, will show you how to get started with FsCheck and it's integration with unit testing frameworks. It will also teach how you can test a game example using model-based testing, which is an extended concept of property-based testing.

This a bonus chapter and can be downloaded from the following link:

What you need for this book

In order to make full use of this book, you should have a development machine where you can run the latest version of Windows with an installation of Visual Studio Community 2013.

The Visual Studio Community 2013 edition is a fully featured IDE that contains everything you need in order to run the examples in this book and get started with F# development. You can download it from Microsoft at

There is an even better test runner provided by JetBrains Resharper that will increase productivity when running test-driven development, but it is not necessary for you to learn about in this book. This book will provide only one example of testing with Resharper, and the rest of the examples are done by the built-in tools of Visual Studio Community 2013 at

Who this book is for

If you are a developer with .NET experience, you will learn through this book how to increase the quality of your deliveries by developing in F# with test automation. Based on what you'll learn, you will benefit from your previous F# experience and also if you've done test automation before in other languages or technologies.


In this book, you will find a number of styles of text that distinguish between different kinds of information. Here are some examples of these styles, and an explanation of their meaning.

Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "We can include other contexts through the use of the include directive."

A block of code is set as follows:

    // assert
    let dbCustomer = CustomerRepository.get customerID
    dbCustomer |> should equal newCustomer

When we wish to draw your attention to a particular part of a code block, the relevant lines or items are set in bold:

let div x y =
  // precondition 
  assert(y > 0)
  assert(x > y)

Any command-line input or output is written as follows:

> parse "MMXIV";;

New terms and important words are shown in bold. Words that you see on the screen, in menus or dialog boxes, for example, appear in the text like this: "In order to get the path to the library you want to reference, right click on References in the Solution Explorer."


Warnings or important notes appear in a box like this.


Tips and tricks appear like this.

Reader feedback

Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or may have disliked. Reader feedback is important for us to develop titles that you really get the most out of.

To send us general feedback, simply send an e-mail to , and mention the book title via the subject of your message.

If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at

Customer support

Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

Downloading the example code

You can download the example code files from your account at for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you.


Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you would report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded on our website, or added to any list of existing errata, under the Errata section of that title.

To view the previously submitted errata, go to and enter the name of the book in the search field. The required information will appear under the Errata section.


Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works, in any form, on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

Please contact us at with a link to the suspected pirated material.

We appreciate your help in protecting our authors, and our ability to bring you valuable content.


You can contact us at if you are having a problem with any aspect of this book, and we will do our best to address it.