Thursday, 28 September 2017

Moq tutorial

1- private methods mock

2-  static method mock
3- public , protected and internal method mock
4- properties unit test and mocking
5-data base method mocking
6- abstract and sealed class mocking and unit test
7- constructor mocking and unit test



Quickstart


Moq is intended to be simple to use, strongly typed (no magic strings!, and therefore full compiler-verified and refactoring-friendly) and minimalistic (while still fully functional!).

Methods

using Moq;

// Assumptions:

public interface IFoo
{
    Bar Bar { get; set; }
    string Name { get; set; }
    int Value { get; set; }
    bool DoSomething(string value);
    bool DoSomething(int number, string value);
    string DoSomethingStringy(string value);
    bool TryParse(string value, out string outputValue);
    bool Submit(ref Bar bar);
    int GetCount();
    bool Add(int value);
}

public class Bar 
{
    public virtual Baz Baz { get; set; }
    public virtual bool Submit() { return false; }
}

public class Baz
{
    public virtual string Name { get; set; }
}


var mock = new Mock<IFoo>();
mock.Setup(foo => foo.DoSomething("ping")).Returns(true);


// out arguments
var outString = "ack";
// TryParse will return true, and the out argument will return "ack", lazy evaluated
mock.Setup(foo => foo.TryParse("ping", out outString)).Returns(true);


// ref arguments
var instance = new Bar();
// Only matches if the ref argument to the invocation is the same instance
mock.Setup(foo => foo.Submit(ref instance)).Returns(true);


// access invocation arguments when returning a value
mock.Setup(x => x.DoSomethingStringy(It.IsAny<string>()))
  .Returns((string s) => s.ToLower());
// Multiple parameters overloads available


// throwing when invoked with specific parameters
mock.Setup(foo => foo.DoSomething("reset")).Throws<InvalidOperationException>();
mock.Setup(foo => foo.DoSomething("")).Throws(new ArgumentException("command"));


// lazy evaluating return value
var count = 1;
mock.Setup(foo => foo.GetCount()).Returns(() => count);


// returning different values on each invocation
var mock = new Mock<IFoo>();
var calls = 0;
mock.Setup(foo => foo.GetCount())
 .Returns(() => calls)
 .Callback(() => calls++);
// returns 0 on first invocation, 1 on the next, and so on
Console.WriteLine(mock.Object.GetCount());

Matching Arguments

// any value
mock.Setup(foo => foo.DoSomething(It.IsAny<string>())).Returns(true);


// matching Func<int>, lazy evaluated
mock.Setup(foo => foo.Add(It.Is<int>(i => i % 2 == 0))).Returns(true); 


// matching ranges
mock.Setup(foo => foo.Add(It.IsInRange<int>(0, 10, Range.Inclusive))).Returns(true); 


// matching regex
mock.Setup(x => x.DoSomethingStringy(It.IsRegex("[a-d]+", RegexOptions.IgnoreCase))).Returns("foo");

Properties

mock.Setup(foo => foo.Name).Returns("bar");


// auto-mocking hierarchies (a.k.a. recursive mocks)
mock.Setup(foo => foo.Bar.Baz.Name).Returns("baz");

// expects an invocation to set the value to "foo"
mock.SetupSet(foo => foo.Name = "foo");

// or verify the setter directly
mock.VerifySet(foo => foo.Name = "foo");
  • Setup a property so that it will automatically start tracking its value (also known as Stub):
// start "tracking" sets/gets to this property
mock.SetupProperty(f => f.Name);

// alternatively, provide a default value for the stubbed property
mock.SetupProperty(f => f.Name, "foo");


// Now you can do:

IFoo foo = mock.Object;
// Initial value was stored
Assert.Equal("foo", foo.Name);

// New value set which changes the initial value
foo.Name = "bar";
Assert.Equal("bar", foo.Name);
  • Stub all properties on a mock (not available on Silverlight):
mock.SetupAllProperties();

Events

// Raising an event on the mock
mock.Raise(m => m.FooEvent += null, new FooEventArgs(fooValue));

// Raising an event on a descendant down the hierarchy
mock.Raise(m => m.Child.First.FooEvent += null, new FooEventArgs(fooValue));

// Causing an event to raise automatically when Submit is invoked
mock.Setup(foo => foo.Submit()).Raises(f => f.Sent += null, EventArgs.Empty);
// The raised event would trigger behavior on the object under test, which 
// you would make assertions about later (how its state changed as a consequence, typically)

// Raising a custom event which does not adhere to the EventHandler pattern
public delegate void MyEventHandler(int i, bool b);
public interface IFoo
{
  event MyEventHandler MyEvent; 
}

var mock = new Mock<IFoo>();
...
// Raise passing the custom arguments expected by the event delegate
mock.Raise(foo => foo.MyEvent += null, 25, true);

Callbacks

var mock = new Mock<IFoo>();
var calls = 0;
var callArgs = new List<string>();

mock.Setup(foo => foo.DoSomething("ping"))
 .Returns(true)
 .Callback(() => calls++);

// access invocation arguments
mock.Setup(foo => foo.DoSomething(It.IsAny<string>()))
 .Returns(true)
 .Callback((string s) => callArgs.Add(s));

// alternate equivalent generic method syntax
mock.Setup(foo => foo.DoSomething(It.IsAny<string>()))
 .Returns(true)
 .Callback<string>(s => callArgs.Add(s));

// access arguments for methods with multiple parameters
mock.Setup(foo => foo.DoSomething(It.IsAny<int>(), It.IsAny<string>()))
 .Returns(true)
 .Callback<int, string>((i, s) => callArgs.Add(s));

// callbacks can be specified before and after invocation
mock.Setup(foo => foo.DoSomething("ping"))
 .Callback(() => Console.WriteLine("Before returns"))
 .Returns(true)
 .Callback(() => Console.WriteLine("After returns"));

Verification

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

// Verify with custom error message for failure
mock.Verify(foo => foo.DoSomething("ping"), "When doing operation X, the service should be pinged always");

// Method should never be called
mock.Verify(foo => foo.DoSomething("ping"), Times.Never());

// Called at least once
mock.Verify(foo => foo.DoSomething("ping"), Times.AtLeastOnce());

// Verify getter invocation, regardless of value.
mock.VerifyGet(foo => foo.Name);

// Verify setter invocation, regardless of value.
mock.VerifySet(foo => foo.Name);

// Verify setter called with specific value
mock.VerifySet(foo => foo.Name ="foo");

// Verify setter with an argument matcher
mock.VerifySet(foo => foo.Value = It.IsInRange(1, 5, Range.Inclusive));

Customizing Mock Behavior

  • Make mock behave like a "true Mock", raising exceptions for anything that doesn't have a corresponding expectation: in Moq slang a "Strict" mock; default behavior is "Loose" mock, which never throws and returns default values or empty arrays, enumerables, etc. if no expectation is set for a member
    var mock = new Mock<IFoo>(MockBehavior.Strict);
  • Invoke base class implementation if no expectation overrides the member (a.k.a. "Partial Mocks" in Rhino Mocks): default is false. (this is required if you are mocking Web/Html controls in System.Web!)
    var mock = new Mock<IFoo> { CallBase = true };
  • Make an automatic recursive mock: a mock that will return a new mock for every member that doesn't have an expectation and whose return value can be mocked (i.e. it is not a value type)
    var mock = new Mock<IFoo> { DefaultValue = DefaultValue.Mock };
    // default is DefaultValue.Empty
    
    // this property access would return a new mock of Bar as it's "mock-able"
    Bar value = mock.Object.Bar;
    
    // the returned mock is reused, so further accesses to the property return 
    // the same mock instance. this allows us to also use this instance to 
    // set further expectations on it if we want
    var barMock = Mock.Get(value);
    barMock.Setup(b => b.Submit()).Returns(true);
  • Centralizing mock instance creation and management: you can create and verify all mocks in a single place by using a MockRepository, which allows setting the MockBehavior, its CallBase and DefaultValue consistently
    var repository = new MockRepository(MockBehavior.Strict) { DefaultValue = DefaultValue.Mock };
    
    // Create a mock using the repository settings
    var fooMock = repository.Create<IFoo>();
    
    // Create a mock overriding the repository settings
    var barMock = repository.Create<Bar>(MockBehavior.Loose);
    
    // Verify all verifiable expectations on all mocks created through the repository
    repository.Verify();

Miscellaneous

  • Setting up a member to return different values / throw exceptions on sequential calls:
    var mock = new Mock<IFoo>();
    mock.SetupSequence(f => f.GetCount())
        .Returns(3)  // will be returned on 1st invocation
        .Returns(2)  // will be returned on 2nd invocation
        .Returns(1)  // will be returned on 3rd invocation
        .Returns(0)  // will be returned on 4th invocation
        .Throws(new InvalidOperationException());  // will be thrown on 5th invocation
  • Setting expectations for protected members (you can't get intellisense for these, so you access them using the member name as a string):
    // at the top of the test fixture
    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);

Advanced Features

// get mock from a mocked instance
IFoo foo = // get mock instance somehow
var fooMock = Mock.Get(foo);
fooMock.Setup(f => f.GetCount()).Returns(42);


// implementing multiple interfaces in mock
var mock = new Mock<IFoo>();
var disposableFoo = mock.As<IDisposable>();
// now the IFoo mock also implements IDisposable :)
disposableFoo.Setup(disposable => disposable.Dispose());

// implementing multiple interfaces in single mock
var mock = new Mock<IFoo>();
mock.Setup(foo => foo.Name).Returns("Fred");
mock.As<IDisposable>().Setup(disposable => disposable.Dispose());


// custom matchers
mock.Setup(foo => foo.DoSomething(IsLarge())).Throws<ArgumentException>();
...
public string IsLarge() 
{ 
  return Match.Create<string>(s => !String.IsNullOrEmpty(s) && s.Length > 100);
}
  • Mocking internal types: Add either of the following custom attributes (typically in AssemblyInfo.cs) to the project containing the internal types — which one you need depends on whether your own project is strong-named or not:
    // This assembly is the default dynamic assembly generated by Castle DynamicProxy, 
    // used by Moq. If your assembly is strong-named, paste the following in a single line:
    [assembly:InternalsVisibleTo("DynamicProxyGenAssembly2,PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]
    
    // Or, if your own assembly is not strong-named, omit the public key:
    [assembly:InternalsVisibleTo("DynamicProxyGenAssembly2")]

Note: When you pass the mock for consumption, you must pass mock.Object, not mock itself.

Linq to Mocks

Moq is the one and only mocking framework that allows specifying mock behavior via declarative specification queries. You can think of Linq to Mocks as:
from the universe of mocks, get me one/those that behave like this (by Fernando Simonazzi)
Keep that query form in mind when reading the specifications:
var services = Mock.Of<IServiceProvider>(sp =>
    sp.GetService(typeof(IRepository)) == Mock.Of<IRepository>(r => r.IsAuthenticated == true) &&
    sp.GetService(typeof(IAuthentication)) == Mock.Of<IAuthentication>(a => a.AuthenticationType == "OAuth"));

// Multiple setups on a single mock and its recursive mocks
ControllerContext context = Mock.Of<ControllerContext>(ctx =>
     ctx.HttpContext.User.Identity.Name == "kzu" &&
     ctx.HttpContext.Request.IsAuthenticated == true &&
     ctx.HttpContext.Request.Url == new Uri("http://moqthis.com") &&
     ctx.HttpContext.Response.ContentType == "application/xml");

// Setting up multiple chained mocks:
var context = Mock.Of<ControllerContext>(ctx =>
     ctx.HttpContext.Request.Url == new Uri("http://moqthis.me") &&
     ctx.HttpContext.Response.ContentType == "application/xml" &&
     // Chained mock specification
     ctx.HttpContext.GetSection("server") == Mock.Of<ServerSection>(config =>
         config.Server.ServerUrl == new Uri("http://moqthis.com/api"));
Linq to Mocks is great for quickly stubbing out dependencies that typically don't need further verification. If you do need to verify later some invocation on those mocks, you can easily retrieve them with Mock.Get(instance).

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

Unit Testing using Moq

What is Moq ?

Moq is a third party library/framework that enables you to create the dummy class and its methods’ dummy implementation without actually creating a class with actual method implementation. Here you need to note that you need to provide the interface name for creating dummy class which will implement interface methods as dummy. This is very useful in the scenarios where you want to test the functionality of a class without implementing the other classes and their methods on which the test candidate class is dependent on.

How to install “Moq” in your test project ?

You can install “Moq’ in your test project using “NuGet Package Manager” UI or console. You can find “Manager NuGet Package” by right clicking on your project solution. When you click on it you will get a UI where you can search “Moq” online and install it to your test project. Now you are ready to go with using “Moq”.

How to use “Moq” in your project to test library classes?

Lets say that you have a class “DefaultMailer” which implements interface “IMailer” with method “SendMail”. SendMail needs an object, of type “IMailClient” as parameter, which will be used to actually send the mail.
Here, IMailer has only four properties, for simplicity, which are necessary to send mail.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace YourNamespace.Utility.Interfaces
{
    public interface IMailer
    {
        string From { get; set; }
        string To { get; set; }
        string Subject { get; set; }
        string Body { get; set; }

        bool SendMail(IMailClient mailClient);
    }
}
IMailClient has only one methods which is used to send mail. It has only two properties i.e. Host and port. Here you can have many MailClients for supported mail servers like gmail, yahoo, hotmail etc.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace YourNamespace.Utility.Interfaces
{
    public interface IMailClient
    {
        string Server { get; set; }
        string Port { get; set; }

        bool SendMail(string from, string to, string subject, string body);
    }
}
DefaultMailer implements IMailer interface.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using YourNamespace.Utility.Interfaces;

namespace YourNamespace.Utility
{
    public class DefaultMailer : IMailer 
    {
        public string From { get; set; }
        public string To { get; set; }
        public string Subject { get; set; }
        public string Body { get; set; }

        public bool SendMail(IMailClient mailClient)
        {
            return mailClient.SendMail(this.From, this.To, this.Subject, this.Body);
        }
    }
}
Now we will see how to test if your DefaultMailer > SendMail method is working as expected. To do this, create a UnitTest project in your solution and install Moq using NuGet package manager. Create a UnitTest class as below.
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using YourNamespace.Utility.Interfaces;
using YourNamespace.Utility;
using Moq;
using Moq.Matchers;

namespace YourNamespace.Utility.TestFixtures
{
    [TestClass]
    public class MailerTestFixtures
    {
        [TestMethod]
        public void SendMailTestFixture()
        {
            //Create a mock object of a MailClient class which implements IMailClient
            var mockMailClient = new Moq.Mock<IMailClient>();

            //Mock the properties of MailClient
            mockMailClient.SetupProperty(client => client.Server, "chat.mail.com").SetupProperty(client => client.Port, "1212");

            //Configure dummy method so that it return true when it gets any string as parameters to the method
            mockMailClient.Setup(client => client.SendMail(It.IsAny<string>(),It.IsAny<string>(),It.IsAny<string>(),It.IsAny<string>())).Returns(true);

            IMailer mailer = new DefaultMailer() { From = "from@mail.com", To="to@mail.com", Subject="Using Moq", Body="Moq is awesome"};

            //Use the mock object of MailClient instead of actual object
            var result = mailer.SendMail(mockMailClient.Object);

            //Verify that it return true
            Assert.IsTrue(result);

            //Verify that the MailClient's SendMail methods gets called exactly once when string is passed as parameters
            mockMailClient.Verify(client => client.SendMail(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
        }
    }
}
Now I will explain the syntax of Moq I have used in the above test case. This is the most simple test case you can use. I have kept it simple here so that you can at least get started with its basics without worrying about the other complex syntax of Moq.

Creating the object of dummy class which implements an interface.

//Create a mock object of a MailClient class which implements IMailClient
var mockMailClient = new Moq.Mock<IMailClient>();
In this example, I have created dummy class which implements the interface IMailClient. The result would be a factory which will give me object of this dummy class by using its property Object.

Setup the properties of dummy class as per your need.

/Mock the properties of MailClient
mockMailClient.SetupProperty(client => client.Server, "chat.mail.com")
              .SetupProperty(client => client.Port, "1212");
You can set the default value for the properties of your dummy class objects using the “SetupProperty” provided by Moq.

Setup the methods of dummy class as per your need.

//Configure dummy method so that it return true when it gets any string as parameters to the method
mockMailClient.Setup(client => client.SendMail(It.IsAny<string>(),It.IsAny<string>(),It.IsAny<string>(),It.IsAny<string>())).Returns(true);
Here we are setting up the SendMail method of your dummy class.  The meaning of the statements is that “When someone invokes the method “SendMail” of dummy class object with four parameters, which may be any string value, then return true. You can modify the statement to configure the cases where user passes null or empty or particular string.

Use the mock/dummy object to test your class “DefaultMailer”

//Use the mock object of MailClient instead of actual object
var result = mailer.SendMail(mockMailClient.Object);

//Verify that it return true
Assert.IsTrue(result);
Here we are using the object of mock/dummy class instead of actual IMailClient implementation. The reason behind this here is that we need to test our class “DefaultMailer” without depending on any other classes. We should assume here that other classes are working fine as we should have written separate test cases to test them.

Verify that the particular method of the interface was invoked

//Verify that the MailClient's SendMail methods gets called exactly once when string is passed as parameters
mockMailClient.Verify(client => client.SendMail(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>()), Times.Once);
Here we verify that the method of the client was actually invoked by DefaultMailer to send mail. We also ensure that the method was invoked just once. In case, it was not invoked or invoked more than once then it will fail the test case.
You can learn more about Moq here.



So if our method is using the database access layer class, then instead of directly creating an object of this class, we can pass the dependency using an interface to the method. The advantage of this approach is that we can easily pass another database access class, or even our mock class, instead of always passing the same class.
mocking framework

Note: Here I have not concentrated on the design for actual implementation of MailClient or MailSender. I have kept it simple so that you can understand Moq without worrying about implementation of actuall MailClient or MailSender.
I hope it will be useful for you to start using Moq to test your methods without creating actual objects of dependency classes. You will learn about the syntax of Moq and get familiar with it as much as you practice. At first you will find it difficult because of its Action, Func, LINQ implementations but once you start using it, you will find it fun and proficient to use Moq.