Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Testing with f#
Testing with f#

Testing with f#: Deliver high-quality, bug-free applications by testing them with efficient and expressive functional programming

eBook
$9.99 $28.99
Paperback
$48.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Table of content icon View table of contents Preview book icon Preview Book

Testing with f#

Chapter 2. Writing Testable Code with Functional Programming

There are three main aspects of writing code in a functional style in F# versus imperative style in a language such as C#:

  • No side effects leads to fewer bugs
  • Smaller isolated units are easier to test
  • Expressiveness makes code right the first time

This chapter will address the following bits about functional programming:

  • Purity
  • Expressiveness
  • Immutability
  • Patterns to help you write testable code

By reading this chapter, you will learn how to write high quality code that will become easy to test. This chapter sets the groundwork for how tests will be written in the following chapters.

Purely functional

What is a computer program?

The following image shows the basic working of a computer program:

Purely functional

An input computed by a program returns an output. This is a very simple concept but it becomes highly relevant for functional programming.

A former colleague told me that's all there is to it: data and code that operates on data. If you want to take it further, the code itself is also data, so a computer program is really just data operating on data.

What about web programming?

The following image shows the basic working of a web server:

Purely functional

It's really the same thing. You have a web request that the server operates on and returns a web response.

How does this apply to functional programming?

The following image shows the basic working of functional programming:

Purely functional

A pure function is very much a computer program. It has an input and output, but the computation of the output adhere to certain conditions:

  • The same output is always guaranteed for the same input
  • The evaluation of the output...

Immutability

The default behavior of F# when using the let keyword is an immutable value. The difference between this and a variable is that the value is not possible to change. With this, there are the following benefits:

  • It encourages a more declarative coding style
  • It discourages side effects
  • It enables parallel computation

The following is an example implementation of the String.Join function using a mutable state:

// F# implementation of String.Join
let join (separator : string) list = 
    // create a mutable state
    let mutable result = new System.Text.StringBuilder()
    let mutable hasValues = false
        
    // iterate over the incoming list
    for s in list do
        hasValues <- true
        result
            .Append(s.ToString())
            .Append(separator)
            |> ignore
            
    // if list hasValues remove last separator
    if hasValues then
        result.Remove(result.Length - separator.Length, separator.Length) |> ignore

    // get result...

Writing testable code

In the previous section we have been looking at basic functional structures that helps us write better programs. Now we're ready to move on to higher level constructs that let us organize our code functionally on a more abstract way.

Active patterns

Pattern matching is one of the killer features of F# that makes it a more attractive language than C# or Visual Basic. It could have been just a nice language feature for the built-in .NET types, but actually it is highly customizable and you can define your own patterns.

Here is how you can define your own active pattern:

// active pattern for sequences
let (|Empty|NotEmpty|) sequence =
    if Seq.isEmpty sequence then Empty
    else NotEmpty sequence

This enables us to use the pattern directly in a match expression:

// example on usage of active pattern
// join ["1"; "2"; "3"] -> "123"
let rec join (s : seq<string>) = 
    match s with
    | Empty -> ""
   ...

Expressiveness through functional programming

There is a very important distinction between programming language paradigms. Two kinds of programming styles stand against each other:

  • Imperative programming
  • Declarative programming

The imperative programming style has its origin in Fortran, and the declarative programming paradigm's roots can be followed back to Lisp. The following sections will compare the two styles and explain why we prefer one over the other in testing.

Imperative programming

Imperative programming has become the standard of programming methodology with the rise of languages such as BASIC, Pascal, C, and C#. It means describing to the computer how to calculate a result, in a way that you would describe how to make a cake:

// imperative programming
let double_imperative numbers =
    let doubled = System.Collections.Generic.List<int>()

    for number in numbers do
        let double = number * 2
        doubled.Add(double)

    doubled 

This code example will double...

Summary

Functional programming is very powerful as it leads to very terse programs with high-quality and low number of faults. This is because good functional code doesn't have any side effects—a place where most of the imperative object-oriented code has its bugs.

In this chapter, we've been looking at functional concepts that make it easier to write good code that doesn't cause side effects and has a low number of bugs, but also code that is easier to test.

The next chapter we'll reach into the toolset that exists for programs written in F# and what it takes to get started with functional testing.

Left arrow icon Right arrow icon
Download code icon Download Code

Description

If you are a developer who wants to test applications using F#, this is the book for you. Basic experience of testing and intermediate experience of functional programming in F# is expected.

Who is this book for?

If you are a developer who wants to test applications using F#, this is the book for you. Basic experience of testing and intermediate experience of functional programming in F# is expected.

What you will learn

  • Set up a test environment in your code base
  • Write unit tests, integration tests, and functional tests for F# applications
  • Leverage tools such as FsUnit, Foq, Canopy, and TickSpec to run tests both inside and outside your development environment
  • Maximize the productivity of your test code using the language features of F#
  • Extract dependencies to databases, web services, and other IO bound operations
  • Test your applications using executable specifications on a web browser
  • Discover the best practices for developing a sustainable test suite

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Feb 20, 2015
Length: 286 pages
Edition : 1st
Language : English
ISBN-13 : 9781784394417
Category :
Languages :

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Billing Address

Product Details

Publication date : Feb 20, 2015
Length: 286 pages
Edition : 1st
Language : English
ISBN-13 : 9781784394417
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $ 141.97
Learning F# Functional Data Structures and Algorithms
$43.99
Testing with f#
$48.99
Mastering F#
$48.99
Total $ 141.97 Stars icon
Banner background image

Table of Contents

11 Chapters
1. The Practice of Test Automation Chevron down icon Chevron up icon
2. Writing Testable Code with Functional Programming Chevron down icon Chevron up icon
3. Setting Up Your Test Environment Chevron down icon Chevron up icon
4. Unit Testing Chevron down icon Chevron up icon
5. Integration Testing Chevron down icon Chevron up icon
6. Functional Testing Chevron down icon Chevron up icon
7. The Controversy of Test Automation Chevron down icon Chevron up icon
8. Testing in an Agile Context Chevron down icon Chevron up icon
9. Test Smells Chevron down icon Chevron up icon
10. The Ten Commandments of Test Automation Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon 3.7
(3 Ratings)
5 star 0%
4 star 66.7%
3 star 33.3%
2 star 0%
1 star 0%
Bohdan Szymanik May 26, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
Great book. It provides a good introduction to software testing in general - useful as I had to recently step in and lead a group of end user testers for a few months - and a great introduction to automated software testing using F# and the readily available test frameworks ie NUnit, xUnit and MSTest, . Don't forget to get the bonus chapter on testing with FsCheck. btw - it's also a great intro to F# programming in general. Really good book.
Amazon Verified review Amazon
Maciek May 26, 2015
Full star icon Full star icon Full star icon Full star icon Empty star icon 4
I believe this is a very interesting book for all people who want to start their adventure with testing using F# and don't know how to do that. The book starts with describing testing as an activity, gradually introducing F# and showing how to configure test environment. It goes through different types of tests: unit, integration and functional as well as it points out test smells and commandments of test automation. At the beginning the book starts with basics going into more details as you go.
Amazon Verified review Amazon
bookworm Feb 04, 2016
Full star icon Full star icon Full star icon Empty star icon Empty star icon 3
This book gives an overview of how to do testing with F# using various testing frameworks. Then gives an overview of various testing methodologies and strategies. This is occasionally interspersed with short rants and "war stories" by the author.Given the price it is ok but I expected more F#, more depth, and less "fluff".
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.