Phillip Trelford's Array

POKE 36879,255

Foq It Easy

Foq is a .Net mocking library with first class support for F# and a cool sounding name. After 9 public releases, Foq is now mature and stable at version 0.9. What started as a 6 to 8 week project ended up more like a half-year project. At this point, I’d like to say a big thank you for the great feedback from the community, and specifically acknowledge the help and support of Mathias Brandewinder, Vasily Kirichenko, Niklas Bergius and Neil Danson. Yesterday the first Foq question appeared on Stack Overflow, thanks to Michael Newton.

F# makes unit testing easy with static method support in xUnit and NUnit, white space in method names and object expressions for mocking simple interfaces:

let [<Test>] ``at 15:00 the sun image should be expected`` () =
    let time = { new ITime with member mock.GetHour() = 15 }
    let calculator = ImageCalculator(time)
    let image = calculator.GetImageForTimeOfDay()
    Assert.AreEqual("sun.jpg",  image)

Foq provides a fluent interface for scaling up to larger interfaces like IList(T), where there are many members, but you may only be interested in specifying return values for a few of them:

let [<Test>] ``setup a method to always return true`` () =
    // Arrange
    let instance =
        Mock<IList>()
            .Setup(fun xs -> <@ xs.Contains(any()) @>).Returns(true)
            .Create()
    // Assert
    Assert.IsTrue(instance.Contains("Anything"))

Foq’s API is quite similar to Moq’s or FakeItEasy’s. Not only does it support LINQ expressions there’s F# Code Quotations too. I tend to think of Code Quotations like classic ASP code blocks <% .. %> for quoting code but with @’s <@ … @>. Code Quotations add a little syntactic noise but come with more expression types than LINQ expressions, so far example you can specify events as you would properties. If however you prefer your lambdas with less symbols then just open the Foq.Linq namespace instead.

Foq also provides some handy shortcuts like the Method method:

let [<Test>] ``setup a method to always return true`` () =
    // Arrange
    let instance =
        Mock<IList>.Method(fun xs -> <@ xs.Contains @>).Returns(true)
    // Assert
    Assert.IsTrue(instance.Contains("Anything"))

Note that even the arguments are omitted from the invocation of Contains for ease.

Where the Method method lets you set up a single method, the With method lets you setup multiple methods with a single method:

Mock<IList<char>>.With(fun xs ->
    <@ xs.Count --> 2 
       xs.Item(0) --> '0'
       xs.Item(1) --> '1'
       xs.Contains(any()) --> true
       xs.RemoveAt(2) ==> System.ArgumentOutOfRangeException()
    @>
)

Here a custom operator –-> is employed to signify returning a value from a member, and the ==> operator raising an exception. For setting up many members, letting go of the heavy fluent interface helps let the actual intent shine through.

Sometimes you just want an instance of an interface mocked which just follows the defaults, and like Moq you can easily specify Mock<T>.Of:

let [<Test>] ``order sends mail if unfilled`` () =
    // setup data
    let order = Order("TALISKER", 51)
    let mailer = Mock.Of<MailService>()
    order.SetMailer(mailer)
    // exercise
    order.Fill(Mock.Of<Warehouse>())
    // verify
    verify <@ mailer.Send(any()) @> once

The mock function lets F# type inference worry about the types for you:

let [<Test>] ``order sends mail if unfilled`` () =
    // setup data
    let order = Order("TALISKER", 51)
    let mailer = mock()
    order.SetMailer(mailer)
    // exercise
    order.Fill(mock())
    // verify
    verify <@ mailer.Send(any()) @> once

Foq support verification of calls as seen above, or you can specify expectations against members and even specific sequence of calls, as you would with the With method:

let xs = Mock<IList<int>>.ExpectSequence(fun xs ->
    <@
        xs.Clear()
        xs.[any()] --> any()
        xs.[any()] <- any()
        xs.Count --> any()
        xs.Contains(any()) --> any()
    @>)

Want to see some more examples, you got it:

All you need to play with Foq is to open an F# project in Visual Studio, Xamarin Studio or Tsunami and pull the Foq library from Nuget or simply reference Foq.fs in your project. Looking forward to more releases and more feedback :)

Prototype

JavaScript is good, so as part of JavaScript the Good Parts, prototypal inheritance must be really, really good.

JS The Good Parts

Some time ago while I was working on a supply chain management system for a large UK based department store I came across some interesting C# code, here’s an example:

public class Customer : Address 
{ 
}

Clarence

Unfortunately Clarence above has no address, but thanks to Homeless Hotspots he is a Mac address. A stark warning of the implications of favouring inheritance over composition.

When asked the C# programmer said that they preferred inheritance as it was quicker to implement in C# than composition. For a single object it is easier to favour inheritance over composition in C#, even more so with C# 2.0 before the advent of auto-implemented properties. Here’s the somewhat more verbose Customer has an Address:

public class Customer
{
    private readonly Address _address = new Address();

    public Address Address 
    { 
        get 
        { 
            return _address; 
        } 
    }
}

The Gang of Four in their seminal Design Patterns book postulated in the first chapter that good object-orientated design should favour composition over inheritance. Unfortunately most people seem to skip the first chapter and dive head first into specific patterns like singleton, proxy and factory. Spring’s AbstractSingletonProxyFactoryBean shows the way:

i-dontalways-make-factory-beans-but-when-i-do-i-make-abstractsingletonproxyfactorybe

Arbitrary misuse of inheritance is not confined to enterprise developers, we only need to look at the Button class in WPF to see a long hierarchy and over 160 members.

Button Inheritance

Thankfully the Intellisense in Visual Studio 2012 has an intelligent search to help you find the needle in the haystack. In the future it may be possible to apply machine learning approaches for prediction so that we can scale from hundreds to thousands of members.

Prototypal Inheritance

Programmers often find JavaScript inheritance hard to understand. This is probably a good thing, creating a pit of success where composition is by default favoured over inheritance.

To this end I have implemented Prototypal Inheritance for C#. The source is available on BitBucket and I will publish a Nuget package for enterprise developers in the near future.

Prototype-based programming is actually quite a natural fit for C# particularly with the dynamic support introduced in C# 4, combined with the var keyword introduced in C# 3, it’s often hard to distinguish C# from JavaScript. 

Now for the science: in prototypal inheritance every object is a clone of another object.

clones


Pseudoclassical

Let’s start with the pseudoclassical JavaScript example from Douglas Crockford’s book:

var Mammal = function (name) { this.name = name; };
Mammal.prototype.get_name = function () { return this.name; };
Mammal.prototype.says = function () { return this.saying || ''; };
var myMammal = new Mammal('Herb the Mammal');
var name = myMammal.get_name(); // 'Herb the Mammal'

var Cat = function (name) {
    this.name = name;
    this.saying = 'meow';
};

Cat.prototype = new Mammal();

Cat.prototype.get_name = function () {
    return this.says() + ' ' + this.name + ' ' + this.says();
};

var myCat = new Cat('Henrietta');
var says = myCat.says(); // 'meow'
var name = myCat.get_name();

You can’t beat a good taxonomy of the animal kingdom to show the awesome power of OO. Now you can create almost exactly the same code in C# using the Prototype library:

var Mammal = Prototype.Constructor<string>((that, name_) => that.Name = name_);
Mammal.Prototype.GetName = (System.Func<dynamic, string>)(that => that.Name);
Mammal.Prototype.Says = (System.Action<dynamic>)(that =>
{
    string saying = that.Saying;
    Echo(saying);
});
var myMammal = Mammal.New("Herb the Mammal");
string herb = myMammal.GetName();
Echo(herb);

var Cat = Prototype.Constructor<string>((that, name_) =>
{
    that.Name = name_;
    that.Saying = "meow";
});

Cat.Prototype = Mammal.New();

var myCat = Cat.New("Henrietta");

string name = myCat.GetName();
Echo(name);
 
Henrietta

Prototypal

Again starting with a JavaScript prototypal example:

var myMammal = {
    name: 'Herb the Mammal',
    get_name: function () {
        return this.name;
    },
    says: function () {
        return this.saying || '';
    }
};

Now in C# taking advantage of anonymous objects:

var Class = Prototype.FromObject(new
{
    Name = "Hello",
    GetName = (System.Func<dynamic, string>)(that => that.Name)
});
dynamic myMammal = Class.New();

There it is, prototypal inheritance for C#, you’re welcome!

Moq.FSharp.Extensions

F# 3 brings first-class support for LINQ Expressions, which makes working with libraries like Moq and FluentValidation easy. A while back I wrote about using Moq with F# 3 and introduced some extension methods to improve the experience for F#. I’ve created a small project called the Moq.FSharp.Extensions currently hosted on BitBucket (the library is about 50 lines of code in a single file), it is also available to download as a Nuget package.

End extension

One thing that was bugging me about using Moq in F# was having to end method setups by ignoring the builder result (in F# you must explicitly ignore return values):

mock.SetupFunc(fun foo -> foo.DoSomething("ping")).Returns(true) |> ignore

While reading Ramon Snir’s answer to using the FluentValidation library in F# over on Stack Overflow, where he adds an Ignore extension method to the builder, it occurred to me to add an End extension method to explicitly end Moq builders:

mock.SetupFunc(fun foo -> foo.DoSomething("ping")).Returns(true).End

any() function

The extensions include some ideas taken from Foq, my own .Net mocking library built for F#. One of the ideas is an any() function which uses F#’s powerful type inference for setting up method arguments on mocks which I find a little easier on the eye than It.IsAny<_>():

mock.SetupFunc(fun foo -> foo.DoSomething(It.IsAny<string>())).Returns(true).End

becomes:

mock.SetupFunc(fun foo -> foo.DoSomething(any()).Returns(true).End

mock function()

The Moq.FSharp.Extensions project includes some examples based on:

The final test in the warehouse example demonstrates the mock() function:

let [<Test>] ``order sends mail if unfilled`` () =
    // setup data
    let order = Order("TALISKER", 51)
    let mailer = mock()
    order.SetMailer(mailer)
    // exercise
    order.Fill(mock())
    // verify
    Mock.Get(mailer).VerifyAction(fun mock -> mock.Send(any()))

Above you can see no type annotations are required at all.

Foq or Moq

The extensions bring some of the ease of use for F# of Foq to Moq. If your tests need to run with F# 2 (Visual Studio 2010) then Foq is a better option as it supports F# Quotations, as well as LINQ Expressions. Otherwise I guess it’s just a matter of taste :)