Mock.Of - how to specify behavior?

4,778 views
Skip to first unread message

TrueWill

unread,
Apr 17, 2011, 4:29:36 PM4/17/11
to Moq Discussions
The new functional specifications syntax is great for specifying
property values. How can I use it to specify method behavior? An
example with Mock.Of specifying the return value of a method with some
parameters would be great. Thanks!

Tim Kellogg

unread,
Apr 17, 2011, 4:43:17 PM4/17/11
to moq...@googlegroups.com
Here is an example 

using (var container = new AutoMockContainer())
{
    var service = container.Mock.Of<IService>();
    service.Setup(x => x.DoSomething());    // And more of the usual Moq setups that we love :)

    // create the subject under test with all dependencies satisfied
    var sut = container.Mock.CreateSut<TestedClass>();
    sut.TestedOperation("hello world");

    // Get the mock again to verify. In this example we also could reuse `service`
    container.Mock.Of<IService>().Verify(x => x.DoSomething(), Times.Exactly(2));
}

We still haven't finished a preview release yet, so any feedback if welcome.

Tim Kellogg


Jason Jarrett

unread,
Apr 17, 2011, 5:01:36 PM4/17/11
to moq...@googlegroups.com
Hello Tim,

I haven't explored the entire api, so sorry if this is way out of context - but based on your recent example, is the Of part in container.Mock.Of<T>() providing any more value than just using container.Mock<T>()?

If it isn't, it might be an annoying extra few characters we'd have to type. (and for what?)

Thoughts?

Tim Kellogg

unread,
Apr 17, 2011, 5:23:34 PM4/17/11
to moq...@googlegroups.com
Jason,

That is a great question. The decision comes from Daniel Cazzulino's suggestion that we not cloud the container's API. As the API develops, more methods and properties will crop up, and it doesn't seem wise to push them into the same naming area along with the other container functionality like registration and resolution. In addition, our container also provides a `.Union<IService, IOtherService>()` method that allows you to use the same mock object for multiple interfaces. i.e.

var container = new AutoMockContainer();
var mock = container.Mock.Union<AccountDAO, IGenericDAO<Account>>();
mock.Setup(x => x.GetById(42)).Returns(new Account());
// and more...

In the example above, the container descends from Castle's WindsorContainer. So if you're project uses Castle, you use the castle container, if you use Autofac you can use the Autofac container, and so on. We don't want to cloud Castle's API (or Autofac, StructureMap, etc) with Unions and other features that could potentially cause name conflicts later on.

Tim Kellogg

Daniel Cazzulino

unread,
Apr 17, 2011, 6:06:23 PM4/17/11
to moq...@googlegroups.com

var mock = Mock.Of<IFoo>(f => f.Do(It.IsAny<int>()) == Mock.Of<IBar>(b => b.IsCool == true));

:)

/kzu from galaxy tab

Jason Jarrett

unread,
Apr 17, 2011, 9:56:08 PM4/17/11
to moq...@googlegroups.com
Thanks for clarifying Tim. I also agree that this makes sense.

Tim Kellogg

unread,
Apr 18, 2011, 11:13:58 AM4/18/11
to moq...@googlegroups.com
Jason,

The reason Daniel wanted the `Mock.Of` syntax is because Moq v4.x has static methods off of the Mock class. So since you can already do:

var mock = Mock.Of<IFoo>(f => f.Do(It.IsAny<int>()) == Mock.Of<IBar>(b => b.IsCool == true));

we thought it would be natural to use the same syntax when using a container:

var mock = container.Mock.Of<IFoo>(f => f.Do(It.IsAny<int>()) == Mock.Of<IBar>(b => b.IsCool == true));

Although, I'd like to add that MoqContrib won't initially support the predicate expression part of `container.Mock.Of(...)` yet (the argument to `Mock.Of<>()`), so this particular example is moot as the library stands currently. We'll be sure to add this feature soon.

Tim Kellogg

Daniel Cazzulino

unread,
Apr 18, 2011, 11:16:53 AM4/18/11
to moq...@googlegroups.com
I don't think the subject of the email indicates that this question was exclusive of the container thing. More of a Mock.Of generic question. Hence my answer ;)

/kzu

--
Daniel Cazzulino | Developer Lead | XML MVP | Clarius Consulting | +1 425.329.3471

Daniel Cazzulino

unread,
Apr 18, 2011, 12:45:10 PM4/18/11
to Tim Kellogg, Kaleb Pederson, moq...@googlegroups.com
Precisely. It returns a mock that behaves in the way you asked (via the predicate).

why is it hard to tell?

I typically use it like that and it's very natural. Actually, I'm starting to dislike more and more the Setup/Returns stuff...

var mock = Mock.Of<IFoo>(f => 
     f.Name == "Foo" && 
     f.Close() == true &&
     f.Submit(It.IsAny<int>()) == Mock.Of<IBar>(b => 
             b.IsCool == true && 
             b.Count == 42 && 
             b.ServiceProvider == Mock.Of<IServiceProvider()));

just convert that to the messy "old" style and see what I mean ;)

/kzu

--
Daniel Cazzulino | Developer Lead | XML MVP | Clarius Consulting | +1 425.329.3471


On Mon, Apr 18, 2011 at 13:23, Tim Kellogg <timothy...@gmail.com> wrote:
Ok, but what does it do? in this example

> var mock = Mock.Of<IFoo>(f => f.Do(It.IsAny<int>()) == Mock.Of<IBar>(b => b.IsCool == true));

I know `mock` will be of type IFoo. but I'm not sure what happens what happens when IFoo.Do(42) is called. I would assume it returns an IBar that has IsCool set to true, but it's really hard to tell. 

Tim Kellogg



On Mon, Apr 18, 2011 at 10:14 AM, Daniel Cazzulino <kzu.net@gmail.com> wrote:
that's what a Where receives.

think of it as "from the universe of mocks, I want one that behaves like this predicate" ;)


/kzu

--
Daniel Cazzulino | Developer Lead | XML MVP | Clarius Consulting | +1 425.329.3471


On Mon, Apr 18, 2011 at 12:01, Tim Kellogg <timothy...@gmail.com> wrote:
And a follow up question... I see that Mock.Of takes a predicate expression. Why a predicate? what happens when the predicate returns true/false?

Thanks,
Tim Kellogg



On Mon, Apr 18, 2011 at 8:49 AM, Tim Kellogg <timothy...@gmail.com> wrote:
Damn...I'll have to read the docs more often. Thanks Daniel :)
Tim Kellogg



On Mon, Apr 18, 2011 at 8:46 AM, Daniel Cazzulino <kzu.net@gmail.com> wrote:
that's what Moq v4 already provides.

the lambda expressions to Of allow you to recursively set any result and its properties/methods in turn too.

in v4, Mock.Of<T> gives you a T, not a Mock<T>.

this syntax is only used for setups, not verify (although that's also a good idea!)


/kzu

--
Daniel Cazzulino | Developer Lead | XML MVP | Clarius Consulting | +1 425.329.3471



On Mon, Apr 18, 2011 at 10:42, Tim Kellogg <timothy...@gmail.com> wrote:
Daniel,

In your emails yesterday, what did you mean by this?

> var mock = Mock.Of<IFoo>(f => f.Do(It.IsAny<int>()) == Mock.Of<IBar>(b => b.IsCool == true));

I didn't plan on adding setups to `.Of<>()` but it's not a bad idea. Can you describe what you had in mind when you wrote this? 

I have a couple issues with it's implications. (1) it implies we might be doing either setups or verifications from `Of`.  (2) I can't think of a way to do both setups and verifications from the same method, so you need to decide what you meant. I don't have a problem with doing shorthand operations, but we need to decide what the requirements are. (3) you use the == operator on a Mock<> object (you would normally do `Mock.Of<IBar>(b => b.IsCool == true).Object`, so this might have been a confusing example). 

Tim Kellogg


TrueWill

unread,
Apr 18, 2011, 2:33:34 PM4/18/11
to Moq Discussions
Thank you very much! This works great. Please consider adding this to
the moq QuickStart!

On Apr 17, 5:06 pm, Daniel Cazzulino <k...@clariusconsulting.net>
wrote:

Tim Kellogg

unread,
Apr 18, 2011, 2:38:53 PM4/18/11
to Daniel Cazzulino, Kaleb Pederson, moq...@googlegroups.com
Daniel,

I completely agree with you that it's easy. However, it's not immediately obvious what you're supposed to do. I suggest adding some documentation to the Moq homepage with lots of examples. I think once people figure out what it's actually doing they'll be so excited they'll never go back to those pesky "Setup" things again. Also, update the XML documentation for the overload that takes a predicate and describe what it does there.

To illustrate why I don't think the predicate is obvious, think of what predicates are usually used for. It usually boils down to "do something if this is true" or "include this item if this it true". Something usually happens or doesn't happen depending on what the predicate returns. Whereas in Moq the bool return type is incidental. You're just using the predicate expression to parse code and do setups differently. I think this is completely fine, I just think you need to document how it's actually used since this is kind of unorthodox usage of a predicate expression.

Tim Kellogg

Daniel Cazzulino

unread,
Apr 18, 2011, 2:52:58 PM4/18/11
to moq...@googlegroups.com, Kaleb Pederson
yeah, I thought about naming it Mock.Of<T>().With(x => .... )

.Where(...) is actually more precise, but may also be confusing, dunno... 

Also, the idea is to also provide a .Where/With method on Mock<T>, so that if you already have a mock variable, you can add more behavior with this new syntax too.

thoughts?

/kzu

--
Daniel Cazzulino | Developer Lead | XML MVP | Clarius Consulting | +1 425.329.3471


Tim Kellogg

unread,
Apr 18, 2011, 2:56:37 PM4/18/11
to moq...@googlegroups.com
Yes, I like those ideas. 

Tim Kellogg

Daniel Cazzulino

unread,
Apr 18, 2011, 2:59:14 PM4/18/11
to moq...@googlegroups.com
.Where or .With? :P


/kzu

--
Daniel Cazzulino | Developer Lead | XML MVP | Clarius Consulting | +1 425.329.3471


Tim Kellogg

unread,
Apr 18, 2011, 3:05:18 PM4/18/11
to moq...@googlegroups.com
How it reads in English:

// get me a mock for IFoo where `.Do(42)` returns null
var mock = Mock.Of<IFoo>().Where(x => x.Do(It.IsAny<int>()) == null);

// versus get me a mock of IFoo with `.Do(42)` returning null
var mock = Mock.Of<IFoo>().With(x => x.Do(It.IsAny<int>()) == null);

I think I like how Where reads better. The only problem, though, is the coincidence that Linq has a `Where` method that takes a predicate and does something very different.

Tim Kellogg

TrueWill

unread,
Apr 18, 2011, 5:59:35 PM4/18/11
to Moq Discussions
As an aside, when you're setting a Boolean return value of true
ReSharper doesn't like it.

var foo = Mock.Of<IFoo>(x => x.MethodReturningBool() == true);

You can leave the == true off (as ReSharper wants you to) but then it
looks REALLY weird.

Daniel Cazzulino

unread,
Apr 18, 2011, 7:17:26 PM4/18/11
to moq...@googlegroups.com
Screw ReSharper ;)


/kzu

--
Daniel Cazzulino | Developer Lead | XML MVP | Clarius Consulting | +1 425.329.3471


TrueWill

unread,
Apr 19, 2011, 12:40:58 PM4/19/11
to Moq Discussions
I know, it doesn't really matter for tests, but a LOT of developers
use ReSharper. And ReSharper's Code Cleanup will remove the "== true"
as redundant. I run that on tests all the time to alphabetize methods.
Just FYI.

Also, what is the correct way to verify expectations on mocks created
with Mock.Of? Should we use

Mock.Get(somethingCreatedWithMockOf).Verify(foo =>
foo.Execute("ping"));

?

Thanks!

Kaleb Pederson

unread,
Apr 19, 2011, 1:11:05 PM4/19/11
to moq...@googlegroups.com
On Tue, Apr 19, 2011 at 9:40 AM, TrueWill <bi...@truewill.net> wrote:
> I know, it doesn't really matter for tests, but a LOT of developers
> use ReSharper. And ReSharper's Code Cleanup will remove the "== true"
> as redundant. I run that on tests all the time to alphabetize methods.
> Just FYI.

I imagine you know, but Resharper's code cleanup is completely
configurable. If that's a feature you want I'd just recommend that you
create a code cleanup profile for your tests that doesn't have that
cleanup behavior. And, if you really wanted, you could even create a
pattern so that R# suggests you add a '== <bool>' when called from
Mock.Of<>(). Similarly, you could disable the default warning and
create two patterns, one that suggest you remove it in normal code and
one that recommends it within Mock.Of.

--Kaleb

Daniel Cazzulino

unread,
Apr 19, 2011, 3:28:58 PM4/19/11
to moq...@googlegroups.com
:)

re:Verify: yes, Mock.Get. 

However, I typically have two types of mocks: those I don't care to verify (aka stubs? ;)) and those I do.

For the ones I do, I'll keep a reference to the Mock<T> and verify later. That's also why I'd like to add a Where/With method to the mock also.


/kzu

--
Daniel Cazzulino | Developer Lead | XML MVP | Clarius Consulting | +1 425.329.3471


Mariano Omar Rodriguez

unread,
Apr 19, 2011, 6:04:06 PM4/19/11
to moq...@googlegroups.com
You don't need to use == true or == false, you can use directly:

var foo = Mock.Of<IFoo>(x => x.MethodReturningBool());

or for false:

var foo = Mock.Of<IFoo>(x => !x.MethodReturningBool());

And the right way to do the verify is exactly what you put:

Mock.Get(somethingCreatedWithMockOf).Verify(foo => foo.Execute("ping"));

Daniel Cazzulino

unread,
Apr 19, 2011, 6:11:16 PM4/19/11
to moq...@googlegroups.com
Hey slacker. About time you answered a question :P


/kzu

--
Daniel Cazzulino | Developer Lead | XML MVP | Clarius Consulting | +1 425.329.3471


TrueWill

unread,
Apr 19, 2011, 9:21:10 PM4/19/11
to Moq Discussions
Excellent. Thank you and kzu too!

On Apr 19, 5:04 pm, "Mariano Omar Rodriguez" <marian...@gmail.com>
wrote:

TrueWill

unread,
Apr 28, 2011, 5:14:44 PM4/28/11
to Moq Discussions
I'm starting to use the Mocks.Of LINQ syntax and like it too!

How do you specify Throws(), Callback(), etc. with the new syntax?

Mariano Omar Rodriguez

unread,
Apr 28, 2011, 5:42:49 PM4/28/11
to Moq Discussions
You need to get the Mock object con "Mock.Get(...)" and after that you can
specify Setup, callback, throws, etc.
You can't specify directly in the LINQ expression, only properties and
methods that returns a value are supported in that syntax.

--
Post: moq...@googlegroups.com
Unsubscribe: moqdisc-u...@googlegroups.com

Reply all
Reply to author
Forward
0 new messages