The new internal architecture of AutoFixture 2.0 enables some interesting features. One of these is that it becomes easy to extend AutoFixture to become an auto-mocking container.

Since I personally use Moq, the AutoFixture 2.0 .zip file includes a new assembly called Ploeh.AutoFixture.AutoMoq that includes an auto-mocking extension that uses Moq for Test Doubles.

Please note that AutoFixture in itself has no dependency on Moq. If you don't want to use Moq, you can just ignore the Ploeh.AutoFixture.AutoMoq assembly.

Auto-mocking with AutoFixture does not have to use Moq. Although it only ships with Moq support, it is possible to write an auto-mocking extension for a different dynamic mock library.

To use it, you must first add a reference to Ploeh.AutoFixture.AutoMoq. You can now create your Fixture instance like this:

var fixture = new Fixture()
    .Customize(new AutoMoqCustomization());

What this does is that it adds a fallback mechanism to the fixture. If a type falls through the normal engine without being handled, the auto-mocking extension will check whether it is a request for an interface or abstract class. If this is so, it will relay the request to a request for a Mock of the same type.

A different part of the extension handles requests for Mocks, which ensures that the Mock will be created and returned.

Splitting up auto-mocking into a relay and a creational strategy for Mock objects proper also means that we can directly request a Mock if we would like that. Even better, we can use the built-in Freeze support to freeze a Mock, and it will also automatically freeze the auto-mocked instance as well (because the relay will ask for a Mock that turns out to be frozen).

Returning to the original frozen pizza example, we can now rewrite it like this:

[Fact]
public void AddWillPipeMapCorrectly()
{
    // Fixture setup
    var fixture = new Fixture()
        .Customize(new AutoMoqCustomization());
 
    var basket = fixture.Freeze<Basket>();
    var mapMock = fixture.Freeze<Mock<IPizzaMap>>();
 
    var pizza = fixture.CreateAnonymous<PizzaPresenter>();
 
    var sut = fixture.CreateAnonymous<BasketPresenter>();
    // Exercise system
    sut.Add(pizza);
    // Verify outcome
    mapMock.Verify(m => m.Pipe(pizza, basket.Add));
    // Teardown
}

Notice that we can simply freeze Mock<IPizzaMap> which also automatically freeze the IPizzaMap instance as well. When we later create the SUT by requesting an anonymous BasketPresenter, IPizzaMap is already frozen in the fixture, so the correct instance will be injected into the SUT.

This is similar to the behavior of the custom FreezeMoq extension method I previously described, but now this feature is baked in.


Comments

How would you compare and contrast AutoFixture with UnityAutoMockContainer? I started using UnityAutoMockContainer and have been very pleased with it so far. The main contribution it makes is that it reduces the friction of TDD by mocking all dependencies so I do not have to. Then I can extract them using syntax like this

Mock<IFoo> mockFoo = _container.GetMock<IFoo>();


It appears that both AutoFixture and UnityAutoMocker can be used in a similar fashion. Though it appears that AutoFixture has a broader feature set (the ability to create anonymous value types.) Whereas, one can create anonymous reference types by simply asking theUnityAutoMockContainer to resolve the interface or concrete type.

I have only been using UnityAutoMockContainer for a week or two. So when I stumbled upon your most excellent book Dependency Injection in .Net, I discovered AutoFixture and was considering whether to use it instead. I welcome your perspective. By the way, that book on DI you are writing is great! Nice work.

2010-09-09 10:34 UTC
Hi David

Thanks for writing.

As a disclaimer I should add that I have no experience with UnityAutoMockContainer, but that I'm quite familiar with Unity itself, as well as the general concept of an auto-mocking container, which (IIRC) is something that predates Unity. At the very least there are many auto-mocking containers available, and you can often easily extend an existing DI Container to add auto-mocking capabilities (see e.g. this simplified example).

This is more or less also the case with AutoFixture. It started out as something completely different (namely as a Test Data Builder) and then evolved. At a time it became natural to also add auto-mocking capabilities to it.

You could say that the same is the case with Unity: it's a DI Container and was never envisioned as an auto-mocking container. However, since Unity is extensible, it is possible to add auto-mocking to it as well (just as the Autofac example above).

This means that UnityAutoMockContainer and AutoFixture approach the concept of auto-mocking from two different directions. I can't really compare their auto-mocking capabilities as I don't know UnityAutoMockContainer well enough, but I can offer this on a more general level:

AutoFixture shares a lot of similarities with DI Containers (Unity included). It supports auto-wiring and it can be configured to create instances in lots of interesting ways. However, since the focus is different, it does some things better and some things not as well as a DI Container.

AutoFixture has more appropriate handling of primitive types. Normally a DI Container is not going to serve you a sequence of unique strings or numbers, whereas AutoFixture does. This was really the original idea that started it all.

Most DI Containers are not going to try to populate writable properties, but AutoFixture does.

AutoFixture also has a more granular concept of what constitutes a request. For all DI Containers I know, a request to resolve something is always based on a Type. AutoFixture, on the other hand, enable us to make arbitrary requests, which means that we can treat a request for a ParameterInfo differently than a request for a PropertyInfo (or a Type) even if they share the same Type. This sometimes comes in handy.

On the other hand AutoFixture is weaker when it comes to lifetime management. A Fixture is never expected to exist for more than a single test case, so it makes no sense to model any other lifestyle than Transient and Singleton. AutoFixture can do that, but nothing more. It has no Seam for implementing custom lifestyles and it does not offer Per Thread or Per HttpRequest lifestyles. It doesn't have to, because it's not a DI Container.

In short I prefer AutoFixture for TDD because it's a more focused tool than any DI Container. On the other hand it means that there's one more new API to learn, although that's not an issue for me personally :)
2010-09-09 11:04 UTC
Hi Mark,

I just started to play with AutoFixture and its auto-mocking support. As far as I can see, the auto-mocking extensions return mocks without functionality, especially, without any data in the properties.
Example:
var anonymousParent = fixture.CreateAnonymous<ComplexParent>();
This example from the cheat sheet would return a filled fixture:
ComplexParent:
-Child: ComplexChild
--Name: string: "namef70b67ff-05d3-4498-95c9-de74e1aa0c3c"
--Number: int: 1


When using the AutoMoqCustomization with an interface IComplexParent with one property Child: ComplexChild, the result is strange:
1) Child is of type ComplexChildProxySomeGuid, i.e. it is mocked, although it is a concrete class
2) Child.Number is 0
3) Child.Name is null


I think this is inconsistent. Is it a bug or intentional? If it is intentional, could you please explain?

Thanks,

Daniel
2011-09-08 09:57 UTC
Yes, this is mostly intentional - mostly because even if AutoFixture would attempt to assign data to properties, you wouldn't get any result out of it. As an illustration, try using Moq without AutoFixture to create a new instance of IComplexParent and assign a property to it. It's not going to remember the property value!

This is, in my opinion, the correct design choice made by the Moq designers: an interface specifies only the shape of members - not behavior.

However, with Moq, you can turn on 'normal' property behavior by invoking the SetupAllProperties on the Mock instance. The AutoMoqCustomization doesn't do that, but it's certainly possible to use the underlying types used to implement it to compose a different AutoMoqCustomization that also invokes SetupAllProperties.

In any case, this is only half of the solution, because it would only enable the Mock instance to get 'normal' property behavior. The other half would then be to make the AutoMoqCustomization automatically fill those properties. This is possible by wrapping the ISpecimenBuilder instance responsible for creating the actual interface instance in a PostProcessor. The following discussions may shed a little more light on these matters: Default Greedy constructor behavior breaks filling and Filling sub properties.

In short, I don't consider it a bug, but I do respect that other people may want different base behavior than I find appropriate. It's definitely possible to tweak AutoFixture to do what you want it to do, but perhaps a bit more involved than it ought to be. AutoFixture 3.0 should streamline the customization API somewhat, I hope.

As a side note, I consider properties in interfaces a design smell, so that's probably also why I've never had any issues with the current behavior.
2011-09-08 10:51 UTC
Thanks for your response. As I am using NSubstitute, I created an auto-mocking customization for it. I used the RhinoMocks customization as a template and changed it to support NSubstitute. I also implemented it the way I expected AutoMoq to behave, i.e. with filled properties.
Please see the fork I created: https://hg01.codeplex.com/forks/dhilgarth/autonsubstitute.
If you are interested, I can send a pull request.
2011-09-08 13:28 UTC
I think it is better to have AutoFixture behave consistent. When I request an anonymous instance, I expect its properties to be filled. I don't care if it's a concrete class I get or a mock because I asked for an anonymous instance of an interface. For me as a user it's not intuitive that they behave differently.
That's why I implemented it that way in AutoNSubstitute.


BTW, AutoMoq is in itself inconsistent: As I wrote in my original question, the property Child is not null but it contains a mock of ComplexChild. I understand your reasons for saying the properties should be null if a mock is returned, but then it should apply consistently to all properties.

Maybe it is a good idea to let the user of the customization choose what behavior he wants?
2011-09-08 14:19 UTC
Yes, I agree that consistency is desirable :)

As I mentioned, it's not something I've ever given a great deal of thought because I almost never define properties on interfaces, but I agree that it might be more consistent, so I've created a work item for it - you could go and vote for it if you'd like :)

Regarding your observation about the Child property, that's once more the behavior we get from Moq... The current implementation of AutoMoq basically just hands all mocking concerns off to Moq and doesn't deal with them any further.

Regarding your fork for NSubstitute I only had a brief look at it, but please do send a pull request - then we'll take it from there :)

Thank you for your interest.
2011-09-08 14:37 UTC


Wish to comment?

You can add a comment to this post by sending me a pull request. Alternatively, you can discuss this post on Twitter or Google Plus, or somewhere else with a permalink. Ping me with the link, and I may add it as a comment.

Published

Thursday, 19 August 2010 19:25:50 UTC

Tags



"Our team wholeheartedly endorses Mark. His expert service provides tremendous value."
Hire me!