Phillip Trelford's Array

POKE 36879,255

Foq 1.6

Foq is a mature open source .Net mocking library written in F#. It’s raison d'être is to enable F# as a unit testing language, for F#, C# or VB.Net code bases.

Foq is part a rich set of testing tools available to F# developers. Use Foq when unit testing in combination with staple .Net testing frameworks like NUnit and xUnit through to F# specific fluent assertion libraries like FsUnit and Unquote. Combine Foq with AutoFixture to simplify test setup even further.


The name Foq is derived from Moq, with Foq providing a familiar fluent interface:

// Moq from C#
var mock = new Mock<ILoveThisFramework>();
mock.Setup(framework => framework.DownloadExists("2.0.0.0"))
   .Returns(true);
ILoveThisFramework lovable = mock.Object;

// Foq from F#
let lovable = 
   Mock<ILoveThisFramework>()
      .Setup(fun framework -> <@ framework.DownloadExists("2.0.0.0") @>)
      .Returns(true)
      .Create()

The main difference in the setups above is that Moq uses mutation where as Foq is thread safe, favouring method chaining to build an immutable representation of the type.

Foq takes advantage of F#’s code quotations and type inference for shorter setups:

// Mock succinctly with Foq
let lovable =
   Mock.With(fun (framework:ILoveThisFramework) ->
   <@ framework.DownloadExists("2.0.0.0") --> true @>)

Getting Started

Get the latest version of Foq from Nuget or simply include Foq.fs in your test project. An F# script packed with examples is included when you install Foq via Nuget.

Then take a peek at some of the many Foq testing examples on CodePlex:

    New features

Back in April 2013, Foq’s API stabilized at version 0.9, since then new features and bug fixes have been requested via CodePlex, StackOverflow and Twitter.

Many of the requests have come from people testing C# codebases from F# and requiring extensive support for:

Testing C# Code

Foq can be used to mock both interfaces and abstract classes. For abstract classes arguments can be passed to the base constructor when the mock is created:

let mock = Mock<AbstractBaseClassWithConstructorArgs>().Create(7, "seven")
Assert.AreEqual("seven", mock.Name)

In F# multiple return values are easily specified using tuples, in C# out parameters are required. To setup C# methods with out parameters using Foq, simply specify the out arguments as tuples as you would normally from F#:

// Calling a method with out arguments from F#
let (success, value) = dict.TryGetValue("Fred")
// Setting up a method with out arguments using Foq
Mock<IDictionary<string,int>>()
   .SetupByName("TryGetValue").Returns((true, 1))
   .Create()

Testing Events

In F# events are first class, meaning they can be created like objects and passed to functions. To setup an event on an interface:

// Arrange
let event = Event<_,_>() 
let instance = 
      Mock<INotifyPropertyChanged>() 
         .SetupEvent(fun x -> <@ x.PropertyChanged @>).Publishes(event.Publish) 
         .Create() 
// Act 
event.Trigger(instance, PropertyChangedEventArgs("Name"))

Non-standard events can be setup using the SetupEventByName method.

Testing F# Code

Foq provides helpers for quickly mocking a single member be it a property:

Mock<MyAbstractBaseClass>.Property(fun x -> <@ x.MyProperty @>).Returns(1)

or a method (note that arguments do not need to be specified):

Mock<GreetingTime>
    .Method(fun gt -> <@ gt.GetGreeting @>)
    .Returns("Good Night")

Foq can now mock F# specific members with curried arguments e.g.

Mock<ICurry>()
    .Setup(fun curry -> <@ curry.Fun (any()) (any()) @>)
    .Returns(true)
    .Create()

Finally Mock.With now supports return values via functions:

Mock<IFoo>.With(fun foo -> 
    <@ 
        foo.Bar(1) --> 1
        foo.Bar(any()) ---> fun () -> 2
    @>)

What next?

Try F# as a testing language for your .Net code bases and use Foq to mock F# and C# types with ease. Then try web testing with canopy, automated acceptance testing using NaturalSpec, TickSpec or SpecFlow or random testing via FsCheck.

NorDevCon 2014

NorDevCon is a one day agile and tech conference held annually in the historic English town of Norwich, also the setting for the recent British comedy Alan Partridge: Alpha Papa.

Last Friday I took the short hop across the Fens to Norwich to talk about Data Science and Machine Learning with F#. First a talk on F# Type Providers entitled All your base types are belong to us (thanks to Ross McKinlay for the meme), and then after lunch a hands on Machine Learning workshop exploring `Titanic passengers using data from Kaggle (a data science company based in San Francisco).

The conference attracted a great range of speakers with some really interesting sessions:

NorDevCont

In the morning I got to chat with Jon Skeet about programming with kids, and then watched him answer stack overflow questions at a frightening pace.

Jason Gorman gave a lively and warm opening keynote on Software Apprenticeships, which included a Skype session with his brave apprentice, Will Price. Immediately followed by Chris O’Dell on Continuous Delivery at 7Digital which ended with a lot of interested questions.

In the afternoon I caught Phil Nash’s thought provoking session on Agile and Mobile – do they work together as well as they should. Phil talked about a schism in testing approaches on mobile platforms, particularly iOS, with some in the community advocating unit testing and TDD and others none at all. Check out Phil’s links from the talk to learn more.

The closing keynote came from the highly respected Nat Pryce and Steve Freeman on Building SOLID Foundations. The talk focused on design principles for addressing complexity in mid-scale codebases. Nat gave examples of successfully taming complexity in an unnamed risk management project using immutability and DSLs, in effect a functional-style approach. An approach that Jessica Kerr also explored in some depth in her popular Functional Principles for Object-Oriented Developers talk at last year’s Øredev.

The day was capped off was a hearty dinner with a fun format where people moved around between the courses.

All your types are belong to us!

My first talk show cased typed access to a vast array of data sources through to software environments like Hadoop and R, via F# Type Providers:


Type Providers covered:

  • JSON, CSV, HTML Tables and the World Bank (via FSharp.Data)
  • SQLite (via Ross’s SQL Provider which also supports MySQL, Oracle, Postgre & SQL Server)
  • R (via BlueMountain Capital’s R-Type Provider)
  • Hadoop (in the browser via Try FSharp)

All of the Type Providers shown are open source projects developed by the F# community, can be easily integrated into projects via Nuget and run on Linux, Mac and Windows.

The HTML Table type provider being the most recent, developed by Colin Bull, it gives immediate typed access to data in tables on web pages.

After the talk Jon Skeet suggested a Protocol Buffers Type Provider:


For which it turns out Cameron Taggart already has a project called Froto.

If you are interested in creating your own Type Provider I’d recommend reading Michael Newtons’s Type Provider tutorial. Michael will be running a free workshop on building Type Providers at the F#unctional Londoners meetup on May 1st.

Hands On Machine Learning workshop

This session gave an introduction to machine learning, using F#’s REPL and the CSV Type Provider to easily explore data on Titanic and predict survival outcomes:


It was a great group and everyone managed to complete the task and produce good prediction results using decision tree learning in just 1.5 hours.

Wrapping Up

Thanks to Paul Grenyer for organizing an excellent conference and giving me the opportunity to speak. Paul put together a really interesting programme which was extremely well-executed.

A++ would recommend :)

F# Eye for the VB Guy

Are you a VB developer curious about functional-first programming. F# is a statically typed language built into Visual Studio. It is a multi-paradigm language with both functional and object-oriented constructs.

F# has powerful type inference which reduces the amount of typing you need to do without reducing performance or correctness.

F# projects are easily referenced from VB and vice versa. Like VB, F# makes minimal use of curly braces, and for many operations the syntax will feel quite familiar.

Here’s my cut-out-and-keep guide to common operations in both languages:

Declaring values

VB.Net F#
' Fully qualified
Dim greeting As String = "Hello"
' Type inferred
Dim greeting = "Hello"
// Fully qualified 
let greeting : string = "Hello"
// Type inferred 
let greeting = "Hello"

 

Declaring functions

VB.Net F#
Sub Print(message As String)
  Console.WriteLine(message)
End Sub

Function Add _
  (a As Integer, b As Integer) _
  As Integer
  Return a + b
End Function
let print( message: string ) = 
  Console.WriteLine(message) 

// Return type is inferred
let add(a:int, b:int) = a + b

 

Loops

VB.Net F#
For i = 1 To 10
  Console.WriteLine("Hello")
Next

For Each c In "Hello"
  Console.WriteLine(c)
Next
for i = 1 to 10 do 
   Console.WriteLine("Hello") 


for c in "Hello" do 
  Console.WriteLine(c)

 

If/Then/Else

VB.Net F#
Dim ageGroup As String
If age < 18 Then
  ageGroup = "Junior"
Else
  ageGroup = "Senior"
End If
let ageGroup = 
  if age < 18 then  
    "Junior"
  else  
    "Senior"
 

 

Pattern Matching

VB.Net F#
' Score Scrabble letter
Select Case
c Case "A", "E", "I", "L", "N", _ "O", "R", "S", "T", "U" Return 1 Case "D", "G" Return 2 Case "B", "C", "M", "P" Return 3 Case "F", "H", "V", "W", "Y" Return 4 Case "K" Return 5 Case "J", "X" Return 8 Case "Q", "Z" Return 10 Case Else Throw New _
      InvalidOperationException()
  End Select
// Score scrabble letter
match letter with
| 'A' | 'E' | 'I' | 'L' | 'N' 
| 'O' | 'R' | 'S' | 'T' | 'U' -> 1
| 'D' | 'G' -> 2
| 'B' | 'C' | 'M' | 'P' -> 3
| 'F' | 'H' | 'V' | 'W' | 'Y' -> 4
| 'K' -> 5
| 'J' | 'X' -> 8
| 'Q' | 'Z' -> 10
| _ -> invalidOp ""

 

Try/Catch

VB.Net F#
Dim i As Integer = 5
Try
  Throw New ArgumentException()
Catch e As OverflowException _
      When i = 5
  Console.WriteLine("First handler")
Catch e As ArgumentException _
      When i = 4
  Console.WriteLine("Second handler")
Catch When i = 5
  Console.WriteLine("Third handler")
End Try
let i = 5
try
  raise (ArgumentException())
with
| :? OverflowException when i = 5 ->
  Console.WriteLine("First handler")
| :? ArgumentException when i = 4 ->
  Console.WriteLine("Second handler")
| _ when i = 5 ->
  Console.WriteLine("Third handler")

 

Modules

VB.Net F#
Module Math
  ' Raise to integer power
  Function Pown( _
    x As Double, y As Integer)
    Dim result = 1
    For i = 1 To y
      result = result * x
    Next
    Return result
  End Function
End Module
module Maths =
  // Raise to integer power
 let pown (x:float,y:int) =
   let mutable result = 1.0
   for i = 1 to y do
     result <- result * x
   result

 

Classes

VB.Net F#
' Immutable class
Public Class Person
  Private ReadOnly myName As String

  Public Sub New(name As String)
    myName = name
  End Sub

  ReadOnly Property Name() As String
    Get
      Return myName
    End Get
  End Property
End Class

' Inheritance
Public Class MyWindow _
  : Inherits Window
End Class
// Immutable class
type Person (name : string) = 
  member my.Name = name

// Inheritance
type MyWindow() =
   inherit Window()

 

Summary

Interested in learning more? Give F# a try in Visual Studio with the built-in F# Tutorial project or in your browser with http://tryfsharp.org