---
title: "Creating a AutoMockingContainer with Microsoft Unity - Pretty darn simple."
url: "https://osherove.com/blog/2008/4/14/creating-a-automockingcontainer-with-microsoft-unity-pretty.md"
canonical: "https://osherove.com/blog/2008/4/14/creating-a-automockingcontainer-with-microsoft-unity-pretty.html"
published: "2008-04-14T07:18:14"
updated: "2008-04-14T07:18:14"
tags: ["Agile", "Testing Guidelines", "Unit Testing"]
author: "Roy Osherove"
description: "updated : made container more readable Just created a little Auto Mocking Container built on Microsoft Unity. It was very very simple. here's a test that uses it. We tell the container to Returna stub for T because we…"
usage: "Licensed under CC BY 4.0 — reuse, quote and adapt with attribution (Roy Osherove, link to the original page)."
license: "https://creativecommons.org/licenses/by/4.0/"
---

# Creating a AutoMockingContainer with Microsoft Unity - Pretty darn simple.

By Roy Osherove April 14, 2008 In [Agile](https://osherove.com/blog/category/agile), [Testing Guidelines](https://osherove.com/blog/category/testing-guidelines), [Unit Testing](https://osherove.com/blog/category/unit-testing)

**Historical article** · Originally published April 14, 2008; technical details may be outdated.

**updated**: made container more readable

Just created a little Auto Mocking Container built on Microsoft Unity. It was very very simple.

here's a test that uses it. We tell the container to Returna stub for T because we will want whoever calls resolve<T> on that interface to get the same mock the we will configure in the record() block. In the record() block we Resolve the interface that returns a mock, and tell the mock what to return. later, "real" code resolves the "Runner" class, which is dependent on our two mocks.

\[Test\]

        public void MockTwoDependenciesForAConstructor()

        {

            MockRepository mocks \= new MockRepository();

            AutoMockingUnityContainer container \=

                           new AutoMockingUnityContainer(mocks);

            container.WillReturnAStubFor<ILogger\>();

            container.WillReturnAStubFor<IEmailer\>();

            using (mocks.Record())

            {   //Tell our mock to return true when this method is called

                container.Resolve<ILogger\>().IsLogFileFull();

                LastCall.Return(true);

            }

            //runner class takes both of these mocks in its constructor

            Runner runner \= container.Resolve<Runner\>();

            Assert.IsNotNull(runner);

        }

and here's the full code for the container. As you can see it is pretty simple. ContainerControlledLifetimeManager makes sure we have one single instance built for that object during the container's lifetime or until the type is re-registered using the container.

     public class AutoMockingUnityContainer : UnityContainer

    {

        private MockRepository mocks;

        public AutoMockingUnityContainer(MockRepository mocks)

        {

            this.mocks \= mocks;

        }

        public AutoMockingUnityContainer WillReturnAStubFor<T\>() where T : class

        {

            return (AutoMockingUnityContainer) this.RegisterType(typeof(T), null, null, new StubFactory(typeof(T), mocks,Lifetime.Singleton));

        }

        public AutoMockingUnityContainer WillCreateMockFor<T\>() where T : class

        {

            return (AutoMockingUnityContainer) this.RegisterType(typeof(T), null, null, new MockFactory(typeof(T),mocks,Lifetime.Singleton));

        }

        public AutoMockingUnityContainer WillCreatePartialMockFor<T\>(Lifetime lifetime) where T : class

        {

            return (AutoMockingUnityContainer) this.RegisterType(typeof(T), null, null, new PartialMockFactory(typeof(T), mocks, lifetime));

        }

        private abstract class AbstractFactory : ContainerControlledLifetimeManager

        {

            protected Type theType;

            protected Lifetime lifetime;

            protected AbstractFactory(Type theType, MockRepository mocks, Lifetime lifetime)

            {

                this.theType \= theType;

                this.lifetime \= lifetime;

                this.mocks \= mocks;

            }

            protected MockRepository mocks;

            protected abstract object GetTheObject(Type type);

            public override object GetValue()

            {

                object value \= base.GetValue();

                if (lifetime\==Lifetime.NewEveryTime || value \== null)

                {

                    value \= GetTheObject(theType);

                    SetValue(value);

                }

                return value;

            }

        }

        class MockFactory: AbstractFactory

        {

            public MockFactory(Type theType, MockRepository mocks, Lifetime lifetime)

                : base(theType, mocks, lifetime)

            {

            }

            protected override object GetTheObject(Type type)

            {

                return mocks.CreateMock(type);

            }

        }

        class StubFactory: AbstractFactory

        {

            public StubFactory(Type theType, MockRepository mocks, Lifetime lifetime)

                      : base(theType, mocks, lifetime)

            {

            }

            protected override object GetTheObject(Type type)

            {

                return mocks.Stub(type);

            }

        }

        class PartialMockFactory: AbstractFactory

        {

            public PartialMockFactory(Type theType, MockRepository mocks,

                          Lifetime lifetime) : base(theType, mocks, lifetime)

            {

            }

            protected override object GetTheObject(Type type)

            {

                return mocks.PartialMock(theType);

            }

        }

    }

    public enum Lifetime

    {

        Singleton,

        NewEveryTime

    }

## More in Agile

[All posts in Agile](https://osherove.com/blog/category/agile)

- Apr 30, 2008

    ### [Unit Testing Denial Pattern #1: Pretending the test is no longer valid](https://osherove.com/blog/2008/4/30/unit-testing-denial-pattern-1-pretending-the-test-is-no-long.html)

- Apr 25, 2008

    ### [Pros and Cons and of using an Auto Mocking container in your tests](https://osherove.com/blog/2008/4/25/pros-and-cons-and-of-using-an-auto-mocking-container-in-your.html)

- Mar 15, 2008

    ### [Belgium TechDays Slides and demos, and my travel schedule](https://osherove.com/blog/2008/3/15/belgium-techdays-slides-and-demos-and-my-travel-schedule.html)

- Mar 9, 2008

    ### [Testing loops?](https://osherove.com/blog/2008/3/9/testing-loops.html)


---

## About the author

**Roy Osherove**: Senior Solutions Architect at AWS working on AI for production and AI-driven development; author of The Art of Unit Testing and Elastic Leadership, with about 20 years of consulting and training on unit testing, TDD, team leadership and continuous delivery.

### Sites

- [RobotPaper](https://robotpaper.ai/): This blog: AI patterns and anti-patterns, AI and coding agents, and engineering leadership.
- [osherove.com](https://osherove.com): Roy's personal site. Author of The Art of Unit Testing and Elastic Leadership; consulting and training on unit testing, TDD, team leadership and continuous delivery, plus about 20 years of blog posts.
- [The Art of Unit Testing](https://www.artofunittesting.com): The Art of Unit Testing, 3rd Edition (Manning): readable, maintainable, trustworthy unit tests, plus TDD workshops in C#, JavaScript, Java and Kotlin.
- [5whys.com](https://www.5whys.com): Roy's writing on software team leadership: self-organizing teams, surviving chaos, learning mode and the Elastic Leadership model.
- [Pipeline Driven](https://pipelinedriven.org): Continuous delivery and DevOps practices: build patterns, pipeline-friendly testing, DevOps metrics and enterprise DevOps.
- [Elastic Leadership](https://www.elasticleadership.com): Elastic Leadership, Roy's framework for software team leaders (survival, learning and self-organizing modes).

### Social

- X: https://x.com/royosherove
- LinkedIn: https://www.linkedin.com/in/osherove/

### Contact

- Contact form: https://forms.gle/jQSx5KoXvrVA1JCK7

### License

Licensed under CC BY 4.0 — reuse, quote and adapt with attribution (Roy Osherove, link to the original page). License: https://creativecommons.org/licenses/by/4.0/
