Moq v4 functional specifications

04/20/11

Moq v4 functional specifications

The Moq mocking library only gets better. Here’s a LINQPad example of the functional specifications introduced in v4.

void Main()
{
    var foo = Mock.Of<IFoo>(f =>
        f.Id == 1 &&
        f.Who == "me" &&
        f.GetBar(It.IsAny<string>()) == Mock.Of<IBar>(
            b => b.Name == "Fred"));

    Console.WriteLine(foo.Id);
    Console.WriteLine(foo.Who);
    Console.WriteLine(foo.GetBar("whatever").Name);

    // If you need verification and still want to use
    // the functional style:
    Mock.Get(foo).Verify(f => f.GetBar("whatever"));
}

public interface IFoo
{
    int Id { get; }
    string Who { get; }
    IBar GetBar(string name);
}

public interface IBar
{
    string Name { get; }
}

This prints:

1
me
Fred

No more having to type "mock.Object"!

For more details, see Old style imperative mocks vs moq functional specifications and this Moq Discussions thread. Note that Daniel Cazzulino (kzu) suggests separating behavior-verification mocks and stubs; this syntax is most useful for stubbing.


Your Host: webmaster@truewill.net
Copyright © 2000-2013 by William Sorensen. All rights reserved.