My favorites | Sign in
moq
Project Home Downloads Wiki Issues Source
Search
for
QuickStart  

Featured
Updated Jun 24, 2010 by kzu.net

Introduction to Moq

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

Methods

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.DoSomething(It.IsAny<string>()))
		.Returns((string s) => s.ToLower());
// Multiple parameters overloads available


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


// lazy evaluating return value
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.GetCountThing())
    .Returns(() => calls)
    .Callback(() => calls++);
// returns 0 on first invocation, 1 on the next, and so on
Console.WriteLine(mock.Object.GetCountThing());

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.DoSomething(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>();
mock.Setup(foo => foo.Execute("ping"))
    .Returns(true)
    .Callback(() => calls++);


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

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

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

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

Verification

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

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

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

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

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 IBar as it's "mock-able"
    IBar 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 MockFactory, which allows setting the MockBehavior, its CallBase and DefaultValue consistently
  • var factory = new MockFactory(MockBehavior.Strict) { DefaultValue = DefaultValue.Mock };
    
    // Create a mock using the factory settings
    var fooMock = factory.Create<IFoo>();
    
    // Create a mock overriding the factory settings
    var barMock = factory.Create<IBar>(MockBehavior.Loose);
    
    // Verify all verifiable expectations on all mocks created through the factory
    factory.Verify();

Miscellaneous

  • 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.Submit()).Returns(true);


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


// custom matchers
mock.Setup(foo => foo.Submit(IsLarge())).Throws<ArgumentException>();
...
public string IsLarge() 
{ 
  return Match<string>.Create(s => !String.IsNullOrEmpty(s) && s.Length > 100);
}
  • Mocking internal types of another project: add the following assembly attribute (typically to the AssemblyInfo.cs) to the project containing the internal types:
  • // This assembly is the default dynamic assembly generated Castle DynamicProxy, 
    // used by Moq. Paste in a single line.
    [assembly:InternalsVisibleTo("DynamicProxyGenAssembly2,PublicKey=0024000004800000940000000602000000240000525341310004000001000100c547cac37abd99c8db225ef2f6c8a3602f3b3606cc9891605d02baa56104f4cfc0734aa39b93bf7852f7d9266654753cc297e7d2edfe0bac1cdcf9f717241550e0a7b191195b7667bb4f64bcb8e2121380fd1d9d46ad2d92d2d15605093924cceaf74c4861eff62abf69b9291ed0a340e113be11e6a7d3113e92484cf7045cc7")]

Read more


Note: when you need to pass the mock for consumption, you must use the mock.Object accessor as a consequence of a C# compiler restriction (vote to get it removed at Microsoft Connect)

Head on to the API documentation, download it and have fun! Engage in the discussion group to give us feedback, share your experiences or wishes for vNext!

Comment by david.ka...@gmail.com, Apr 6, 2009

Is there a way to view the old 2.6 QuickStart? We haven't quite ported over and it's a nice reference.

Comment by jcss...@gmail.com, Apr 9, 2009

It looks like you can see the old wiki pages in svn, http://code.google.com/p/moq/source/browse/wiki/QuickStart.wiki?r=477

Comment by danny.er...@gmail.com, Apr 23, 2009

Hi, I'm newbie using VSE2008 that doesn't come with any unit test.

I've downloaded the Moq, so whats next? where to put the dll? how to create a unit test?

Appreciate if any one can help.

Thanks a lot.

Comment by benoit...@gmail.com, May 7, 2009

@danny.erunner Moq is a mocking framework which is only a part of unit testing. I'd suggest you take a look at NUnit or MbUnit? for unit tests

Comment by fosta...@gmail.com, Jun 29, 2009

There are a few old/unanswered discussions going around regarding how to mock a reference parameter. The quickstart guide provides us with a way of mocking a reference parameter which has a particular value but it is still unclear regarding whether it is possible how to (a) mock 'any' reference parameter and (b) change the value of that reference parameter in callback. Would it be possible to get some clarification on whether moq is capable of this, and if so, how?

Comment by dlangdon...@gtempaccount.com, Jul 15, 2009

Suppose I want to do a unit test on classA.method1(int x, int y, int z)

classA.method1, in turn, calls classB.method2(int x, int y, int z, ref string msg)

It seems that it is impossible to mock classB.method2 because "msg", the argument to method2 is called inside method1, but it says in the documentation that to match my mock setup, msg must be the same instance as the string in my setup!

What can I do?

Comment by ryan.mcd...@gmail.com, Jul 17, 2009

"I've downloaded the Moq, so whats next? where to put the dll?"

Good question. Is the install REALLY so simple that it's not worth mentioning? I'm coming from the linux world, so I'm used to readme files, installation instructions, man pages, etc. The post above proves I'm not the only one with this sentiment - why not put up a couple of sentences explaining how to install moq (I'd suggest the top of the quickstart page). Thanks.

Comment by nathap...@gmail.com, Aug 27, 2009

Ryan,

Just add reference to moq.dll to your project in Visual Studio and you are good to go!

Comment by randol...@gmail.com, Sep 21, 2009

@ryan.mcdonald82:

To expand on @nathapolw's post:

You can simply download the zip file and extract it to a known location, then add a file reference to the moq.dll (using the "Browse" tab that appears in the Visual Studio "Add Reference..." command.

Comment by darcy.pa...@gmail.com, Nov 3, 2009

I had some trouble understanding callbacks for multi-argument methods; here's what worked for me. If it's correct, could you consider adding it?

// access invocation arguments
mock.Setup(foo => foo.Execute(It.IsAny<int>(), It.IsAny<string>()))
    .Returns(true)
    .Callback<int, string>((int i, string s) => calls.Add(s));
Comment by bharathr...@gmail.com, Nov 24, 2009

Can anyone explain to me how to verify the mocks created using mock factory explicitly?? mockfactory.verify() wont do. I want to be able to verify the mocks explicitly.Please send in your comments.

Comment by aboimpi...@gmail.com, Jan 15, 2010

Hello,

I want to mock a System.Web.UI.Page. I have a method that receive the Page and according with some parameters like Page.Request.CurrentExecutionFilePath?.

How can I mock the Page?

I created a Page object but I cannot use this.

Can Moq help me?

Regards Paulo Aboim Pinto Odivelas - Portugal

Comment by david.ka...@gmail.com, Jan 19, 2010

I'm assuming that this QuickStart is for 3.1 and not the 4.0 beta, but it would be nice to have a version posted to avoid confusion.

Comment by yura...@gmail.com, Feb 3, 2010

CallBack?: // access invocation arguments when returning a value // Multiple parameters overloads available

Is there any way to have more than 4 arguments? (in other words, is there a way to use the CallBack? with custom delegate instead of System.Action<>?)

Comment by jeanpier...@gmail.com, Feb 14, 2010

// Causing an event to raise automatically when Submit is invoked mock.Setup(foo => foo.Submit()).Raises(f => f.Sent += null, EventArgs?.Empty);

doesn't work (no intellisense on .Raises)

Comment by jeanpier...@gmail.com, Feb 14, 2010

In answer to how to raise an event automatically when a method is called...

See http://groups.google.com/group/moqdisc/browse_thread/thread/e9777d3ad69a8e5a/71d0aeff091ca17e?lnk=gst&q=event#71d0aeff091ca17e

The answer is to use Callback, as follows:

mockFoo.Setup(foo => foo.Execute()).Callback(()=> mockFoo.Raise(mf => mf.FooEvent? += null, EventArgs?.Empty));

Comment by omaralzabir@gmail.com, Mar 6, 2010

I would recommend a quick tips on using Moq with Conditional Compilers Directives to do both Unit and integration test from same code. http://is.gd/9rXNv

Comment by jason.le...@gmail.com, Mar 19, 2010

@yurachi,

I ran into the same problem today. I solved it by downloading the source code and adding additional callbacks. You will also need to write some additional Action generics as the .Net 3.5 versions only go up to 4. I believe the .Net 4 versions are much wider, and I would bet Moq will adapt to that change with .Net 4 goes GA.

Comment by kristoph...@gmail.com, Jun 11, 2010

FWIW, coming in with little knowledge of Moq, I found the very first lines confusing:

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

I found this confusing because I thought that maybe IFoo had a method called "ping", which was going to be executed/mocked by Moq. I thought Execute() might be a Moq thing, similar to the "Expect" or "Allow" methods of other mocking frameworks.

To make it less confusing for dummies like me, I'd recommend providing some sort of declaration for IFoo (so it's clear what its methods are), and ensuring that example string arguments don't look like method names.

Comment by project member kzu.net, Jun 24, 2010

Replaced the Executes with DoSomething?. Should I use Bar() instead?

Comment by kristoph...@gmail.com, Jul 8, 2010

I'd prefer Bar(), but no big deal. I'd also change "ping" to "some string" or something else that is obviously not a method name.

Thanks!

Comment by adigital...@gmail.com, Jul 27, 2010

Is it possible to reset the count of times a method was executed on a mock?

Following an arrange, act, assert pattern, sometimes the arrange results in calls to the mock, as well as the act. My assert of Times needs to take into account both calls, so I need to state that there are two calls. This ends up passing when there is one in arrange and one in act.

This seems messy, and isn't really what is intended. There might be two calls during arrange, none in act, and the test would still pass.

Is this a situation Moq can handle?

Comment by fda...@gmail.com, Aug 10, 2010

http://www.dimecasts.net/Casts/CastDetails/8

Direct link to the screencast listed for "Introduction to Mocking with Moq (Video)"

Comment by leonidch@gmail.com, Aug 22, 2010

I have a class and a method m1 that calls another method m2 of the same class. I need to know how many times m1 calls m2. But Moq shows as if it doesn't call at all. this test passes: mock.verify(p=>p.m1(), Times.Once(), errorMessage); mock.verify (p=>p.m2(), Times.Never(), errMsg2); However mock.Verify (p=>p.m2(), Times.Once(), err) passes too. thanks in advance

Comment by leonidch@gmail.com, Aug 22, 2010

more practical version of my previous question - if a method m2 calls method m1 of another class from different assembly i get the same problem. this test passes: actual = mock2.object.m2(mock1.object); mock2.Verify (x=>x.m2(mock1.object), Times.Once(), errMsg2); mock1.Verify (x=>x.m1(), times.Never(), errMsg1). what am i missing?

Comment by sol...@gmail.com, Sep 22, 2010

Hi! please, tell me, how I may to use mocks in async invokation? In fact, I must ask for the behavior of the method to call and order, which takes the answer. Am I right?

Comment by Normand....@gmail.com, Dec 8, 2010

I am using moq.protected to mock a method a protected virtual method of a class. When my test executes, the mock "dont work", the mocked method is called for real. When I do a VerifyAll? on my mock, I got a "The following setups were not matched: ......"

Here is my code:


var myMoq = new Mock<MyClass>(MockBehavior?.Default, new object { null, null });

User user = UnitTestHelper?.GetUserTest1?(); bridgeMoq.Protected().Setup<User>("GetUserByName?", ItExpr?.IsAny?<string>()).Returns(user);

MyClass_Accessor? target = new MyClass_Accessor? (null, null); target.MethodXThatCallsGetUserByNameFunction()

... ...


I want to unit test a private method of a class (MethodXThatCallsGetUserByNameFunction). This method calls other method of that class(GetUserByName?) that I want to mock, to isolate the test of this specific function(MethodXThatCallsGetUserByNameFunction).

Any idea why the function GetUserByName? is called "for real" during my unit test, and why the mock does not works, returning my User object specified in the Setup?

Thanks

Comment by somaylov...@gmail.com, Jan 5, 2011

We can use other function at place mock is it possible rply@Pankajkumarkharwar@gmail.com

Comment by mauro.ma...@gmail.com, Feb 22, 2011

Is is possible to Moq Sharepoint sealed classes? I cant find any information on this anywhere - all I find is "use TypeMock? Isolator" which isnt allowed on my project.

Comment by Andrew.L...@gmail.com, Mar 4, 2011

Is there a version of moq that works with the latests version of Castle.Core 2.5.2?

Comment by mphillip...@gmail.com, Apr 12, 2011

is moq being maintained anymore? I am very disappointed if this is the case. As per the message above it has a dependency on Castle.Core 2.5.0 and has not been updated to use the latest version of Castle Core which is causing me issues - any way this can be resolved? I have been championing Moq for a while for its ease of use and syntax - can someone please advise so I can either dump it and find something else or continue using it with the knowledge it is going to be updated - I look forward to any comments ;-)

Comment by remi.des...@gmail.com, Apr 29, 2011

@mphillip - given that a new download was put up on April 12, I would venture a guess that it is still being maintained.

Comment by j...@jonathan.net, May 24, 2011

Check out this 12-part comparison of Moq, Rhino and NSubstitute (NEW):

http://www.richard-banks.org/2010/07/mocking-comparison-part-1-basics.html

Comment by zmeipi...@gmail.com, May 30, 2011

<a href="http://www.beatsfromdredrebeats.com/">dre dre beats</a>

<a href="http://www.beatsfromdredrebeats.com/">cheap beats by dre</a>

<a href="http://www.beatsbydre-beats.com/">beats by dre</a>

<a href="http://www.beatsbydre-beats.com/">cheap beats by dre</a>

Comment by zmeipi...@gmail.com, May 30, 2011

monster beats by dre

beats by dre

cheap beats by dre

Comment by russell....@gmail.com, Jun 29, 2011

Hi all, new blog post on Moq's argument matchers over at:

http://www.russellallen.info/post/Unit-Testing-Good-Patterns-3-Know-Your-Moq-Argument-Matchers!.aspx

"This post is going to be a fairly in depth run through of the core two It methods - It.IsAny?<T> and It.Is<T>(a => a....) - followed by a quick skim through the less used It.IsInRange? and It.IsRegex? methods."

Comment by pankajgu...@gmail.com, Nov 1, 2011

Hi, how to use if condition using moq,actually I want to do some operation if it returns true. my code is:-

If lcolObjectsMeClass.Verify(Function(fw) fw.CheckClass?(It.Is?(Of String)(Function(s) s.Contains(lstrString))), Times.Exactly(1)) Then

End If

but the above is giving error "Expression doesnot Produce a value"

And can we use for or foreach loop using moq??

Thanks

Comment by rschmau...@hotmail.com, Nov 10, 2011

Hi, it seems to be, that the Raises(...) Method is not provided by the ISetup interface, so the following code snippet from the docuementation does not work.

mock.Setup(foo => foo.Submit()).Raises(f => f.Sent += null, EventArgs?.Empty);

Do I forget something or what's wrong? Thanks in advance

Comment by camron.b...@gmail.com, Nov 21, 2011

I have made a video on how to test using Moq along with dependency injection and Unity

http://www.youtube.com/watch?v=UiOC1jsQI1o

Comment by rennes....@gmail.com, Nov 28, 2011

How to configure .Setup for this method?

"IEnumerable<TEntity> GetPaged?<KProperty>(int pageIndex, int pageCount, Expression<Func<TEntity, KProperty>> orderByExpression, bool ascending);"

Thanks...

Comment by patri...@gmail.com, Dec 14, 2011

An alternative way of returning different values on each invocation is to use SetupSequence. This allows one more explicit control over the setup if you expect a predetermined number of calls to the setup method.

// returning different values on each invocation (alternative)
var mock = new Mock<IFoo>();
mock.SetupSequence(foo => foo.GetCountThing())
    .Returns(0).Returns(1);
// returns 0 on first invocation, 1 on the second (strict blows up after that; non-strict returns default(T))
Console.WriteLine(mock.Object.GetCountThing());
Comment by rally2...@gmail.com, Dec 27, 2011

I don't see a way to publicly update this Wiki page, but I was going to add a like to the "Read More" section. I made a project on GitHub? for interactively learning Moq, named the Mock Koans (in the spirit of RubyKoans?).

https://github.com/rally25rs/MoqKoans

If someone administrative could add it to the "Read More" section, I would appreciate it!

Comment by fabiocar...@gmail.com, Jan 15, 2012

the link "The automated testing continuum" is dead.

Comment by t.koehn....@gmail.com, Feb 7 (4 days ago)

most "Read more" urls are broken


Sign in to add a comment
Powered by Google Project Hosting