User Tools

Site Tools


technical_notes:public:20131015-cs-moq-cookbook

Parent

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>();
mock.Protected()
     .Setup<int>("Execute")
     .Returns(5);
 
// if you need argument matching, you MUST use ItExpr rather than It
// planning on improving this for vNext
mock.Protected()
    .Setup<string>("Execute",
        ItExpr.IsAny<string>())
    .Returns(true);

Sources : https://github.com/Moq/moq4/wiki/Quickstart

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