User Tools

Site Tools



C# - Moq - Cookbook

Gettings started page

How to verify a method has been called ?

mock.Verify(foo => foo.Execute("ping"));

How to mock protected property ?

You can mock internal property (only if it's virtual property or method).

// In using declaration
using Moq.Protected;
// in the test
var mock = new Mock<CommandBase>();
// if you need argument matching, you MUST use ItExpr rather than It
// planning on improving this for vNext

Sources :

How to mock an event ?

How to mock extension methods ?

internal class Security : ISecurity
    private IPerson person;
    public Security(IPerson person)
        this.person = person;
    public Permissions GetPermissions(Uri resource)
        // get the real permissions for the person
        // field we have received, for the given resource
        throw new NotImplementedException();
public static class SecurityExtensions
    public static Func<IPerson, ISecurity> SecurityFactory = person => new Security(person);
    public static ISecurity Security(this IPerson person)
        return SecurityFactory(person);

Sources : How to mock extension methods (by Daniel Cazzulino)

technical_notes/public/20131015-cs-moq-cookbook.txt · Last modified: 2014/02/13 11:49 by Fabien Arcellier