Daniel Cazzulino's Blog :

Moq (RSS)

Posts related to the Moq mocking framework
Do you really care about Stub vs Mock?

I've argued in the past that this theoretical discussion is utterly useless. In my experience you need slightly different things from your test doubles at different times and depending on the scenarios and what you care about testing in a particular test.

If you're not using any mock/stub framework, you're typically creating manual test aids that morph (so that you can reuse them) as your tests evolve, and end up encompassing a mixture of a fake (i.e. you might put in an in-memory implementation), a stub (flags to tell you whether given members were called) and a mock (you might provide delegates to execute when members are executed, so that you can throw/callback/whatever). I've done this countless times before jumping to a framework/library to help me with this, and I know this is the continuum most developers live in.

Yet, we still see discussions like Rhino Mocks 3.5 Design Decisions: The role of Stub vs. Mock, were the user is asked to make a choice that he will seldom understand without reading the theoretical background. This is counter-productive IMO.

Compare the original two versions with Moq's version:

public void When_user_forgot_password_should_save_user()
{
    var userRepository = new Mock<IUserRepository>();
    var smsSender = new Mock<ISmsSender>();

    var theUser = new User { HashedPassword = "this is not hashed password" };

    userRepository.Expect(x => x.GetUserByName("ayende")).Returns(theUser);

    var controllerUnderTest = new LoginController(userRepository.Object, smsSender.Object);

    controllerUnderTest.ForgotMyPassword("ayende");

    userRepository.Verify(x => x.Save(theUser));
}

As you see, the way you use the "mock" is what makes it look more like a stub or a "true" mock (i.e. you verify all expectations, and you create it with MockBehavior.Strict). You don't have to pick a Stub vs Mock.

This simplifies the learning curve on the framework, and basically allows you to set intuitive options that don't force you entirely in one way or the other (the combination of Expect...Verifiable...Verify allows for VERY flexible usage).

I hope just like everyone's now seeing the value of NOT having an explicit record-reply model, we'll move past this rigid theoretical frame and into a more pragmatic and flexible view of mocking in general.

posted Saturday, July 05, 2008 11:49 AM by kzu with 1 Comments

Mocking protected members with Moq

If you're familiar with Moq, you know that it relies on lambda expressions heavily. This is very good as you get full support from intellisense and refactoring features in Visual Studio. However, it also means you're for the most part restricted to setting expectations on things that your code has access too (public or internal members).

This is especially annoying with protected members, which are very common in template method pattern, factory methods, etc. In this case, you can't simply set an expectation with a lambda expression, as you have no access from the "outside" to the protected member. Being an important scenario, though, we wanted to add support for it.

We could have just extend the core Mock<T> API and add loosely-typed members that received strings (i.e. mock.Expect("Foo")). This would have been bad from the guidance point of view, as it would make for an easy path to "hell" for people not familiar with lambda expression ("mmm... I could use this overload with that lambda thinghy, or just use the simpler string-based overload..."). We'd much rather keep people using strong-typed, lambda-based expectations rather than jumping at the ease of strings.

So, we reached a compromise: we implemented protected expectations using strings, but it will only work for non-public members :). We also didn't want to make this functionality too easy to discover, so we expose it as an extension method that you enable by importing the Moq.Protected namespace:

using Moq.Protected;

then you use the Protected "extension point":

var mock = new Mock<CommandBase>();
mock.Protected()
     .Expect<int>("Execute")
     .Returns(5);

The Expect overload receiving a type parameter specifies the return value from the invocation. You also have ExpectGet/Set members, which expose the same functionality of the strong-typed lambda versions.

Note how rather than polluting the main API with extension overloads receiving strings, we hang all members from the IProtectedMock returned from the Protected() method call. That's an interesting use of extension methods I think, which you also get to see quite a lot in newer C# 3.5 libraries such as Autofac and Umbrella.

Another difference in the invocation style for expectations is the argument matching. Here, I couldn't find an easier way to specify then than using a separate class, ItExpr to specify them:

mock.Protected()
    .Expect<string>("Execute",
        ItExpr.IsAny<string>())
    .Returns(true);

The need for this is subtle, and lies in the fact that the Expect method is not receiving a lambda expression, unlike the strong-typed version, and the alternatives were far worse. So basically ItExpr is an expression-returning version of the It class. I still haven't figured out how you would use custom matchers in this scenario. I guess it would involve building the expression trees just like we do to reconstruct the same expression that would result from using the matcher in the lambda Expect.

 

If you want to play with it, just go ahead and get the latest version from Google Code.

Don't forget to give us feedback through the discussion list or issue tracker.

Enjoy!

posted Saturday, July 05, 2008 10:09 AM by kzu with 2 Comments

Moq 2.5 shipped: lots of good news!

Today we shipped Moq v2.5. It's been a while since RC1 (a month or so feels  so long for an open source agile project!) and we god very good feedback and suggestions for the final release. I'm pretty happy with the current drop and felt it was time for a new stable release.

The change log is quite extensive and yet there are quite a few fixes and improvements here and there that are not reflected in it. Over the next few posts I'll be showcasing the various new features. For now, here's the log:

Version 2.5

  • Added support for mocking protected members
  • Added new way of extending argument matchers which is now very straightforward
  • Added support for mocking events
  • Added support for firing events from expectations
  • Removed usage of MBROs which caused inconsistencies in mocking features
  • Added ExpectGet and ExpectSet to better support properties, and provide better intellisense.
  • Added verification with expressions, which better supports Arrange-Act-Assert testing model (can do Verify(m => m.Do(...)))
  • Added Throws<TException>
  • Added mock.CallBase property to specify whether the virtual members base implementation should be called
  • Added support for implementing, setting expectations and verifying additional interfaces in the mock, via the new mock.As<TInterface>() method (thanks Fernando Simonazzi!)
  • Improved argument type matching for Is/IsAny  (thanks Jeremy.Skinner!)

My personal favorites: streamlined custom matchers (you can completely replace the built-in It.IsXXX matchers), mocking events and adding interfaces to a mock (I'll expand on those soon).

Go ahead and get the latest version from Google Code.

As usual, we'd love to hear your feedback at the discussion list or issue tracker, and patches are always welcome :)

posted Friday, July 04, 2008 7:10 PM by kzu with 2 Comments

A practical example on how to mock static classes without TypeMock

WCF is the second biggest framework after ASP.NET that sooner or later forces you to use a static "context" property to do anything beyond the trivial stuff. ASP.NET has the HttpContext.Current, whereas WCF has the WebOperationContext.Current for example.

My friend Pablo Cibraro proves how you can quite easily make your implementations that depend on such static contexts testable without resorting to black-magic voodoo TypeMock kind of stuff. Any .NET developer can trivially introduce an indirection to make their classes testable, even if they depend on static classes.

So, don't buy a product just because you're lazy and want to avoid creating a few wrapper classes and interfaces. Most of them can be copied directly from Reflector's API rendering. And once you have the interfaces, you can just use MoQ or Rhino (or whichever mock framework you like) to mock them any way you want.

Always use the simplest thing that could possibly work.

Update: added a reference to other mock frameworks that can be used to the same effect. Apparently some people get picky if you have a preference and it happens to be the one you built :)

Update II: For those that didn't follow the discussion over at Roy's blog, I'll repeat an analogy that better explains what my point was with my previous post on mocking statics:

If you are not careful enough and can shoot yourself in the foot, the less shotguns you have around the house, the better.

That said, you may have a big, ugly, old contender where you really need the biggest shotgun you can get. But you'll be giving it to your very best guys, not to the newbie soldier.

Better to teach the newbies how to shoot smaller objectives with a regular pistol first (the whole point of Pablo's post on mocking WCF static context).

Some may say this sounds somewhat paternalist. I think that's pragmatism.

I'd rather show developers how to work around statics imposed by some "legacy" framework they happen to use (i.e. WCF and ASP.NET static contexts) by using typical OO techniques such as the one explained by Pablo, than giving them a bazooka and spending endless hours explaining how to NOT overuse it.

For the record, the technique is *exactly* the same used the ASP.NET MVC team, I don't hear anyone calling HttpContextBase and friends "utterly useless wrappers". I find it hard to think about a case where such a technique could not be applied to make new code written to interact/integrate with a legacy system testable. Would love to find a counter example.

Sometimes it's just that the solution ends up being much simpler than you initially thought. How hard do you think it is to do the ASP.NET MVC trick for the ASP.NET HttpContext? Go get the sources, find class MvcHandler and see for yourself.

Also, Pablo clarified that his original post was how to mock the WCF context, regardless of its static nature (as you could still pass it to your implementation's constructor), when it's neither an interface, nor a class with any virtuals that enable easy mocking.

More to the case against statics and singletons at Scott's blog.

posted Sunday, May 18, 2008 9:00 PM by kzu with 6 Comments

Improving MoQ to allow arrange-act-assert testing style

Today, the MoQAPI lets you setup expectations and later verify them, like so:

[Fact]
public void FillingRemovesInventoryIfInStock()
{
    //arrange/setup
    var order = new Order(TALISKER, 50);
    var mock = new Mock<IWarehouse>();

    //setup - expectations
    mock.Expect(x => x.HasInventory(TALISKER, 50)).Returns(true);
//act
    order.Fill(mock.Object);

    //assert
    Assert.True(order.IsFilled);
    //verify interaction
    mock.VerifyAll();