Changing Windsor lifestyles after the fact

Monday, 26 April 2010 05:09:42 UTC

I recently had the need to change the lifestyles of all components in a WindsorContainer (read on to the end if you want to know why). This turned out to be amazingly simple to do.

The problem was this: I had numerous components registered in a WindsorContainer, some of them as Singletons, some as Transients and yet again some as PerWebRequest. Configuration was even defined in numerous IWindsorInstallers, including some distributed XML files. I now needed to spin up a second container with the same configuration as the first one, except that the lifestyles should be all Singletons across the board.

This can be easily accomplished by implementing a custom IContributeComponentModelConstruction type. Here's a simple example:

Consider this IWindsorInstaller:

public class FooInstaller : IWindsorInstaller
{
    #region IWindsorInstaller Members
 
    public void Install(IWindsorContainer container,
        IConfigurationStore store)
    {
        container.Register(Component
            .For<IFoo>()
            .ImplementedBy<Foo>()
            .LifeStyle.Transient);
    }
 
    #endregion
}

The important point to notice is that it registers the lifestyle as Transient. In other words, this container will always return new Foo instances:

var container = new WindsorContainer();
container.Install(new FooInstaller());

We can override this behavior by adding this custom IContributeComponentModelConstruction:

public class SingletonEqualizer :
    IContributeComponentModelConstruction
{
    public void ProcessModel(IKernel kernel, 
        ComponentModel model)
    {
        model.LifestyleType = LifestyleType.Singleton;
    }
}

In this very simple example, I always set the lifestyle type to the same value, but obviously we can write as complex code in the ProcessModel method as we would like. We can now configure the container like this:

var container = new WindsorContainer();
container.Kernel.ComponentModelBuilder
    .AddContributor(new SingletonEqualizer());
container.Install(new FooInstaller());

With this configuration we will now get the same instance of Foo every time we Resolve IFoo.

We did I need this? Because my application is a web application and I'm using the PerWebRequest lifestyle in a number of places. However, I needed to spin up a second container that would compose object hierarchies for a background process. This background process needs the same component configuration as the rest of the application, but can't use the PerWebRequest lifestyle as there will be no web request available to the background process. Hence the need to change lifestyles across the board.


Why I'm migrating from MSTest to xUnit.net

Monday, 26 April 2010 04:30:49 UTC

About a month ago I decided to migrate from MSTest to xUnit.net, and while I am still in the process, I haven't regretted it yet, and I don't expect to. AutoFixture has already moved over, and I'm slowly migrating all the sample code for my book.

Recently I was asked why, which prompted me to write this post.

I'm not moving away from MSTest for one single reason. It's rather like lots of small reasons.

When I originally started out with TDD, I used nUnit - it was more or less the only unit testing framework available for .NET at the time. When MSTest came, the change was natural, since I worked for Microsoft at the time. This is not the case anymore, but it still took me most of a year to finally abandon MSTest.

There was one thing that really made me cling to MSTest, and that was the IDE integration, but over time, I started to realize that this was the only reason, and even that was getting flaky.

When I started to think about all the things that left me dissatisfied, making the decision was easy:

  • First of all, MSTest isn't extensible, but xUnit.net is. In xUnit.net, I can extend the Fact or Theory attributes (and I intent to), while in MSTest, I will have to play with the cards I've been dealt. I think I could live with all the other issues if I could just have this one, but no.
  • MSTest has no support for parameterized test. xUnit.net does (via the Theory attribute).
  • MSTest has no Assert.Throws, although I requested this feature a long time ago. Now Visual Studio 2010 is out, but Assert.Throws is still nowhere in sight.
  • MSTest has no x64 support. Tests always run as x86. Usually it's no big deal, but sometimes it's a really big deal.
  • In MSTest, to write unit tests, you must create a special Unit Test Project, and those are only available for C# and VB.net. Good luck trying to write unit tests in a more exotic .NET language (like F# on Visual Studio 2008). xUnit.net doesn't have this problem.
  • MSTest uses Test Lists and .vsmdi files to maintain test lists. Why? I don't care, I just want to execute my tests, and the .vsmdi files are in the way. This is particularly bad when you use TFS, but I'm also moving away from TFS, so that wouldn't have continued to be that much of an issue. Still: try having more than one .sln file with unit tests in the same folder, and watch funny things happen because they need to share the same .vsmdi file.
  • I suppose it's because of the .vsmdi files, but sometimes I get a Test run error if I delete a test and run the tests immediately after. That's a false positive, if anyone cares.
  • MSTest gives special treatment to its own AssertionException, which gets nice formatting in the Test Results window. All other exceptions (like verification exceptions thrown by Moq or Rhino Mocks are rendered near-intelligible because MSTest thinks it's very important to report the fully qualified name of the exception before its message. Most of the time, you have to open the Test Details window to see the exception message.
  • Last, but not least, I often get cryptic exception messages like this one: Column 'id_column, runid_column' is constrained to be unique.  Value '8c84fa94-04c1-424b-9868-57a2d4851a1d, d7471c5e-522f-43d3-b2c5-8f5cab55af0e' is already present. This appears in a very annoying modal MessageBox, but clicking OK and retrying usually works, although sometimes it even takes two or three attempts before I can get past this error.

It not one big thing, it's just a lot of small, but very annoying things. After three iterations (VS2005, VS2008 and now VS2010) these issue have still to be addressed, and I got tired of waiting.

So far, I can only say that I have none of these problems with xUnit.net and the IDE integration provided by TestDriven.NET. It's just a much smoother experience with much less friction.


Comments

Hi Mark,

Interesting post about moving away from "out-of-the-box" Microsoft tools. I've made this move about a year ago, and I can't regret about it.

Another point that you mentioned in your post and that really caught my attention was the fact that you are also moving away from TFS. Since I'm starting my own startup here, the budget is really short and we are looking for cheaper alternatives to TFS.

Here, we really like Mercurial HG and we are basing out SCM on it. However, I'm having difficulty finding tools for bug and feature tracking. Can you share with me in which direction you are moving away from TFS?
2010-04-26 13:59 UTC
Personally, I also use Hg for SCM.

In Safewhere, we are currenlty trying out AgileZen for work item tracking. For AutoFixture, I just use the tools provided with CodePlex.
2010-04-26 16:32 UTC
I started with NUnit, and gave a quick shot at MSTest, but never made the transition, because I couldn't see any upside. Could you comment a bit on why you picked xUnit over NUnit? I haven't tried it yet, but from what I saw in the docs, the syntax is pretty interesting; first time in a while that I see a framework which seems to re-think unit testing, rather than improve on JUnit.
2010-04-26 21:15 UTC
There are two main reasons that I prefer xUnit.net over NUnit, but both may be due to ignorance about NUnit on my part. The last time I did serious work with NUnit must have been back in 2005.

One reason is that xUnit.net has a pretty good extensibility story, and as I do have some plans in that direction, that's a pretty big issue for me. Last time I checked, the extensibility story for NUnit didn't match xUnit.net.

NUnit has a design bug when it comes to Fixture management, because it creates only a single instance of a test class and invokes all the test methods on that instance. This may have been fixed since the last time I looked, but in any case, I better like xUnit.net's philosphy of using the test class' constructor for Fixture Setup (if any) and implementing IDisposable for Fixture Teardown.

As I said, both items are based on somewhat dated knowledge on my part, so none of them may apply anymore.
2010-04-26 21:26 UTC
Thanks for writing this up, the tooling built into VS for MSTest makes it very attractive but it still gets a lot of hate. Nice to know why :)
2010-05-11 10:36 UTC
Is the MSTest code going to also be available somewhere? I'd hate to have to constantly be translating for code you already have available for us. - twitter @MaslowJax
2010-06-19 16:46 UTC
I'm not sure exactly to which MSTest code you are referring, but in general I don't plan to change the existing MSTest code I've posted here on the blog. However, new tests are likely to appear with xUnit.net. In any case, when it comes to unit testing examples I don't think the differences are all that important. In most cases it's just a question of differently named attributes and slightly different Assert syntax...
2010-06-20 06:39 UTC
Fabricio #
MSTest support parametrized tests using Pex
2012-03-27 15:17 UTC

AutoFixture 1.1

Saturday, 10 April 2010 10:25:23 UTC

AutoFixture 1.1 is now available on the CodePlex site! Compared to the Release Candidate, there are no changes.

The 1.1 release page has more details about this particular release, but essentially this is the RC promoted to release status.

Release 1.1 is an interim release that addresses a few issues that appeared since the release of version 1.0. Work continues on AutoFixture 2.0 in parallel.


Dependency Injection is Loose Coupling

Wednesday, 07 April 2010 19:49:11 UTC

It seems to me that I've lately encountered a particular mindset towards Dependency Injection (DI). People seem to think that it's only really good for replacing one data access implementation with another. Once you get to that point, you know that the following argument isn't far behind:

“That's all well and good, but we know for certain that we will never exchange [insert name of RDBMS here] with anything else in this application.”

Apart from the hubris of making such a bold statement about the future of any software endeavor, such a statement reveals the narrow view on DI that its only purpose is for replacing data access components - and perhaps for unit testing.

Those are relevant reasons for using DI, but they are only some of the reasons. Let's briefly revisit why we employ DI.

We use DI to enable loose coupling.

DI is only a means to an end. Even if you never intend to replace your database and even if you never want to write a single unit test, DI still offers benefits in form of a more maintainable code base. The loose coupling gives you better separation of concerns because it allows you to apply the Open/Closed Principle.

Example coming right up:

Imagine that we need to implement a PrécisViewModel class with a TopSellers property that returns an IEnumerable<string>. To implement this class, we have a data access component. Let's use the ubiquitous Repository pattern and define IProductRepository to see where that leads us:

public interface IProductRepository
{
    IEnumerable<Product> SelectTopSellers();
}

We can now implement PrécisViewModel like this:

public class PrécisViewModel
{
    private readonly IProductRepository repository;
 
    public PrécisViewModel(IProductRepository repository)
    {
        if (repository == null)
        {
            throw new ArgumentNullException("repository");
        }
 
        this.repository = repository;
    }
 
    public IEnumerable<string> TopSellers
    {
        get
        {
            var topSellers = 
                this.repository.SelectTopSellers();
            return from p in topSellers
                   select p.Name;
        }
    }
}

Nothing fancy is going on here. It's just straight Constructor Injection at work.

Obviously, we can now implement and use a SQL Server-based repository:

var repository = new SqlProductRepository();
var vm = new PrécisViewModel(repository);

So what does all this loose coupling buy us? It doesn't seem to help us a lot.

The real benefit is not yet apparent, but it should become more obvious when we start adding requirements. Let's start with some caching. It turns out that the SelectTopSellers implementation is slow, so we would like to add some caching somewhere.

Where should we add this caching functionality? Without loose coupling, we would more or less be constrained to adding it to either PrécisViewModel or SqlProductRepository, but both have issues:

  • First of all we would be violating the Single Responsibility Principle (SRP) in both cases.
  • If we implement caching in PrécisViewModel, other consumers of the SelectTopSellers would not benefit from it.
  • If we implement caching in SqlProductRepository, it wouldn't be available for any other IProductRepository implementations.

Since the premise for this post is that we will never use any other database than SQL Server, implementing caching directly in SqlProductRepository sounds like the correct choice, but we would still be violating the SRP, and thus making our code more difficult to maintain.

A better solution is to introduce a caching Decorator like this one:

public class CachingProductRepository : IProductRepository
{
    private readonly ICache cache;
    private readonly IProductRepository repository;
 
    public CachingProductRepository(
        IProductRepository repository, ICache cache)
    {
        if (repository == null)
        {
            throw new ArgumentNullException("repository");
        }
        if (cache == null)
        {
            throw new ArgumentNullException("cache");
        }
 
        this.cache = cache;
        this.repository = repository;
    }
 
    #region IProductRepository Members
 
    public IEnumerable<Product> SelectTopSellers()
    {
        return this.cache
            .Retrieve<IEnumerable<Product>>("topSellers",
                this.repository.SelectTopSellers);
    }
 
    #endregion
}

For completeness sake is here the definition of ICache:

public interface ICache
{
    T Retrieve<T>(string key, Func<T> readThrough);
}

The point is that CachingProductRepository extends any IProductRepository we provide to it (including SqlProductRepository) without modifying it. Thus, we have satisfied both the OCP and the SRP.

Just to drive home the point, let us assume that we also wish to record execution times for various methods for purposes of SLA compliance. We can do this by introducing yet another Decorator:

public class PerformanceMeasuringProductRepository : 
    IProductRepository
{
    private readonly IProductRepository repository;
    private readonly IStopwatch stopwatch;
 
    public PerformanceMeasuringProductRepository(
        IProductRepository repository, 
        IStopwatch stopwatch)
    {
        if (repository == null)
        {
            throw new ArgumentNullException("repository");
        }
        if (stopwatch == null)
        {
            throw new ArgumentNullException("stopwatch");
        }
 
        this.repository = repository;
        this.stopwatch = stopwatch;
    }
 
    #region IProductRepository Members
 
    public IEnumerable<Product> SelectTopSellers()
    {
        var timer = this.stopwatch
            .StartMeasuring("SelectTopSellers");
        var topSellers = 
            this.repository.SelectTopSellers();
        timer.StopMeasuring();
        return topSellers;
    }
 
    #endregion
}

Once again, we modified neither SqlProductRepository nor CachingProductRepository to introduce this new feature. We can implement security and auditing features by following the same principle.

To me, this is what loose coupling (and DI) is all about. That we can also replace data access components and unit test using dynamic mocks are very fortunate side effects, but the loose coupling is valuable in itself because it enables us to write more maintainable code.

We don't even need a DI Container to wire up all these repositories (although it sure would could be helpful). Here's how we can do it with Pure DI:

IProductRepository repository =
    new PerformanceMeasuringProductRepository(
        new CachingProductRepository(
            new SqlProductRepository(), new Cache()
            ),
        new RealStopwatch()
    );
var vm = new PrécisViewModel(repository);

The next time someone on your team claims that you don't need DI because the choice of RDBMS is fixed, you can tell them that it's irrelevant. The choice is between DI and Spaghetti Code.


Comments

Arnis L #
That was marvelous post. Never thought about this kind of approach.

Btw, i never figured out if there is anything why service locator isn't anti pattern. :)
2010-04-08 11:27 UTC
Thanks :)

I'm not sure I understand your comment regarding Service Locator. It is an anti-pattern :)

No, seriously, I never expected the entire world to just accept my word as gospel, and there are many people who disagree on this point. Did you have something specific in mind?
2010-04-08 11:37 UTC
I recently listened to a short talk by the MonoTorrent author at FOSDEM 2010. His presentation included an explanation of how (after running into maintenance hell first) he had separated the different concerns in his bittorrent piece picking code by implementing it as a series of decorators.

For me the interesting thing about the talk was that apparently this "separation of concerns" thing had been an important enough discovery for him that it warranted the use of half the presentation time to explain, with the other half being spent talking about the dangers of multi-threading :-)
2010-04-09 07:24 UTC
Kshitij #
Love, the blog spot. thanks for showing DI in action.
2010-04-19 00:01 UTC
Totally off-topic comment, but I believe this is the first time I witness C# code with acute accents :) Do you really use accents in your code?
2010-04-26 21:20 UTC
He he, no, normally I don't, but sometimes when writing sample code I like taking advantage of the fact that C# is based on Unicode. Somewhere here, I also have a sample that uses Danish characters (æ, ø or å), but I can't remember which post it was :)
2010-04-26 21:30 UTC
Hey Mark,
A little off-topic, but how'd you implement Cache to force evaluation if it gets passed a Func<IEnumerable<Something>>? Else it will just cache the query.
2010-10-08 22:17 UTC
Yes, you are right. Perhaps it will just cache the query - it actually depends on what the concrete implementation is. It may be an array or List<T>, in which case there is no issue.

However, we could always specialize the implementation of the cache so that if T was IEnumerable, we'd invoke ToList() on it before caching the result.
2010-10-09 07:04 UTC
Geat post, this shows clearly how you can chain functionality without violation OCP and SRP
2011-04-07 08:34 UTC
Tom Stickel #
Awesome as usual. Once I drank in the Mark Seemann punch, I'm addicted to following how to do DI properly.
Thanks Mark. Any books from you scheduled for this year or the next?

2012-01-15 19:04 UTC
Thanks, Tom. No new book scheduled right now :)
2012-01-15 19:33 UTC
Alex #
Hi Mark!

What if IProductRepository has 15 methods but only one method should be cached?

Or what if I don't need always the cache? So I have a ProductService that needs a IProductRepository. For 5 cases the ProducrtService would need the CachingProductRepository and for the rest the standard ProductRepository?
2012-09-12 11:46 UTC
If you have 15 methods and only one should be cached, you can still cache the one method with a Decorator. The remaining 14 methods on that Decorator can be implemented as pure delegation.

However, if you have this scenario, could it be that the interface violates the Interface Segregation Principle?
2012-09-12 11:56 UTC

Mapping types with AutoFixture

Tuesday, 06 April 2010 05:22:32 UTC

In my previous posts I demonstrated interaction-based unit tests that verify that a pizza is correctly being added to a shopping basket. An alternative is a state-based test where we examine the contents of the shopping basket after exercising the SUT. Here's an initial attempt:

[TestMethod]
public void AddWillAddToBasket()
{
    // Fixture setup
    var fixture = new Fixture();
    fixture.Register<IPizzaMap>(
        fixture.CreateAnonymous<PizzaMap>);
 
    var basket = fixture.Freeze<Basket>();
 
    var pizza = fixture.CreateAnonymous<PizzaPresenter>();
 
    var sut = fixture.CreateAnonymous<BasketPresenter>();
    // Exercise system
    sut.Add(pizza);
    // Verify outcome
    Assert.IsTrue(basket.Pizze.Any(p => 
        p.Name == pizza.Name), "Basket has added pizza.");
    // Teardown
}

In this case the assertion examines the Pizze collection (you did know that the plural of pizza is pizze, right?) of the frozen Basket to verify that it contains the added pizza.

The tricky part is that the Pizze property is a collection of Pizza instances, and not PizzaPresenter instances. The injected IPizzaMap instance is responsible for mapping from PizzaPresenter to Pizza, but since we are rewriting this as a state-based test, I thought it would also be interesting to write the test without using Moq. Instead, we can use the real implementation of IPizzaMap, but this means that we must instruct AutoFixture to map from the abstract IPizzaMap to the concrete PizzaMap.

We see that happening in this line of code:

fixture.Register<IPizzaMap>(
    fixture.CreateAnonymous<PizzaMap>);

Notice the method group syntax: we pass in a delegate to the CreateAnonymous method, which means that every time the fixture is asked to create an IPizzaMap instance, it invokes CreateAnonymous<PIzzaMap>() and uses the result.

This is, obviously, a general-purpose way in which we can map compatible types, so we can write an extension method like this one:

public static void Register<TAbstract, TConcrete>(
    this Fixture fixture) where TConcrete : TAbstract
{
    fixture.Register<TAbstract>(() =>
        fixture.CreateAnonymous<TConcrete>());
}

(I'm slightly undecided on the name of this method. Map might be a better name, but I just like the equivalence to some common DI Containers and their Register methods.) Armed with this Register overload, we can now rewrite the previous Register statement like this:

fixture.Register<IPizzaMap, PizzaMap>();

It's the same amount of code lines, but I find it slightly more succinct and communicative.

The real point of this blog post, however, is that you can map abstract types to concrete types, and that you can always write extension methods to encapsulate your own AutoFixture idioms.


Comments

I also prefer Register (instead of Map). Because most of the times it will be like that: registering an interface to an implementation.
2011-03-13 10:06 UTC

AutoFixture 1.1 RC1

Friday, 02 April 2010 06:44:27 UTC

AutoFixture 1.1 Release Candidate 1 is now available on the CodePlex site.

Users are encouraged to evaluate this RC and submit feedback. If no bugs or issues are reported within the next week, we will promote RC1 to version 1.1.

The release page has more details about this particular release.


Freezing mocks

Saturday, 27 March 2010 13:27:02 UTC

My previous post about AutoFixture's Freeze functionality included this little piece of code that I didn't discuss:

var mapMock = new Mock<IPizzaMap>();
fixture.Register(mapMock.Object);

In case you were wondering, this is Moq interacting with AutoFixture. Here we create a new Test Double and register it with the fixture. This is very similar to AutoFixture's built-in Freeze functionality, with the difference that we register an IPizzaMap instance, which isn't the same as the Mock<IPizzaMap> instance.

It would be nice if we could simply freeze a Test Double emitted by Moq, but unfortunately we can't directly use the Freeze method, since Freeze<Mock<IPizzaMap>>() would freeze a Mock<IPizzaMap>, but not IPizzaMap itself. On the other hand, Freeze<IPizzaMap>() wouldn't work because we haven't told the fixture how to create IPizzaMap instances, but even if we had, we wouldn't have a Mock<IPizzaMap> against which we could call Verify.

On the other hand, it's trivial to write an extension method to Fixture:

public static Mock<T> FreezeMoq<T>(this Fixture fixture)
    where T : class
{
    var td = new Mock<T>();
    fixture.Register(td.Object);
    return td;
}

I chose to call the method FreezeMoq to indicate its affinity with Moq.

We can now rewrite the unit test from the previous post like this:

[TestMethod]
public void AddWillPipeMapCorrectly_FreezeMoq()
{
    // Fixture setup
    var fixture = new Fixture();
 
    var basket = fixture.Freeze<Basket>();
    var mapMock = fixture.FreezeMoq<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
}

You may think that saving only a single line of code may not be that big a deal, but if you also need to perform Setups on the Mock, or if you have several different Mocks to configure, you may appreciate the encapsulation. I know I sure do.


Comments

I am still not sure which problem is solved by a SUT factory like autofixture.

You mentioned that adding an indirection between the tests and the SUT constructor helps with refactoring. But if I add a dependency to the SUT, I will still have to add calls to "fixture.Register" to fix my tests. And if I remove a dependency, then my tests will still work but the setup code will accumulate unnecessary cruft. It might be preferable to get a compiler error about a constructor argument which no longer exists.

My own approach for minimizing the impact of refactorings on tests is to just store the SUT and mocks as fields of the test class, and create them in the TestInitialize/SetUp method. That way there is only one place were the constructor is called.
2010-03-27 20:24 UTC
Wim, thank you for writing.

Setting up your Test Fixture by populating fields on the test class is a common approach. However, I prefer not to do this, as it binds us very hard to the Testcase Class per Fixture pattern. Although it may make sense in some cases, it requires us to add new test classes every time we need to vary the Test Fixture even the slightest, or we will end up with a General Fixture, which again leads to Obscure Tests.

In my opinion, this leads to an explosion of test classes, and unless you are very disciplined, it becomes very difficult to figure out where to add a new test. This approach generates too much friction.

Even without AutoFixture, a SUT Factory is superior because it's not tied to a single test class, and if desirable, you can vary it with overloads.

The added benefit of AutoFixture is that its heuristic approach lets you concentrate on only the important aspects of a particular test case. Ideally, AutoFixture takes care of everything else by figuring out which values to supply for all those parameters you didn't explicitly supply.

However, I can certainly understand your concern about unnecessary cruft. If we need a long sequence of fixture.Register calls to register dependencies then we certainly only introduce another level of maintainance hell. This leads us into an area I have yet to discuss, but I also use AutoFixture as an auto-mocking container.

This means that I never explicitly setup mocks for all the dependencies needed by a SUT unless I actually need to configure it. AutoFixture will simply analyze the SUT's constructor and ask Moq (or potentially any another dymamic mock) to provide an instance. This approach works really well, but I have yet to blog about it because the AutoFixture API that supports automocking has not yet solidified. However, for hints on how to do this with the current version, see this discussion.
2010-03-28 09:02 UTC
Wes #
I think there is a problem with the code sample you provided. I looked at the source code and did a small test.
I think the following is what you meant (or maybe this article i
// does not work
var td = new Mock();
fixture.Register(td.Object);

// should work
fixture.Inject(td.Object);

fixture.Register(() => td.object);
2014-05-14 14:24 UTC

Wes, thank you for writing. You are indeed correct that this particular overload of the Register method no longer exists, and Inject is the correct method to use. See this Stack Overflow answer for more details.

2014-05-15 09:33 UTC
Tommy Vernieri #

This article is out of date. Readers wishing to use AutoFixture with Moq should read AutoFixture as an auto-mocking container.

2018-08-27 02:21 UTC

More about frozen pizza

Friday, 26 March 2010 22:01:42 UTC

In my previous blog post, I introduced AutoFixture's Freeze feature, but the example didn't fully demonstrate the power of the concept. In this blog post, we will turn up the heat on the frozen pizza a notch.

The following unit test exercises the BasketPresenter class, which is simply a wrapper around a Basket instance (we're doing a pizza online shop, if you were wondering). In true TDD style, I'll start with the unit test, but I'll post the BasketPresenter class later for reference.

[TestMethod]
public void AddWillPipeMapCorrectly()
{
    // Fixture setup
    var fixture = new Fixture();
 
    var basket = fixture.Freeze<Basket>();
 
    var mapMock = new Mock<IPizzaMap>();
    fixture.Register(mapMock.Object);
 
    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
}

The interesting thing in the above unit test is that we Freeze a Basket instance in the fixture. We do this because we know that the BasketPresenter somehow wraps a Basket instance, but we trust the Fixture class to figure it out for us. By telling the fixture instance to Freeze the Basket we know that it will reuse the same Basket instance throughout the entire test case. That includes the call to CreateAnonymous<BasketPresenter>.

This means that we can use the frozen basket instance in the Verify call because we know that the same instance will have been reused by the fixture, and thus wrapped by the SUT.

When you stop to think about this on a more theoretical level, it fortunately makes a lot of sense. AutoFixture's terminology is based upon the excellent book xUnit Test Patterns, and a Fixture instance pretty much corresponds to the concept of a Fixture. This means that freezing an instance simply means that a particular instance is constant throughout that particular fixture. Every time we ask for an instance of that class, we get back the same frozen instance.

In DI Container terminology, we just changed the Basket type's lifetime behavior from Transient to Singleton.

For reference, here's the BasketPresenter class we're testing:

public class BasketPresenter
{
    private readonly Basket basket;
    private readonly IPizzaMap map;
 
    public BasketPresenter(Basket basket, IPizzaMap map)
    {
        if (basket == null)
        {
            throw new ArgumentNullException("basket");
        }
        if (map == null)
        {
            throw new ArgumentNullException("map");
        }
 
        this.basket = basket;
        this.map = map;
    }
 
    public void Add(PizzaPresenter presenter)
    {
        this.map.Pipe(presenter, this.basket.Add);
    }
}

If you are wondering about why this is interesting at all, and why we don't just pass in a Basket through the BasketPresenter's constructor, it's because we are using AutoFixture as a SUT Factory. We want to be able to refactor BasketPresenter (and in this case particularly its constructor) without breaking a lot of existing tests. The level of indirection provided by AutoFixture gives us just that ability because we never directly invoke the constructor.

Coming up: more fun with the Freeze concept!


Comments

Interesting, interesting!
It's not clear from the example how using AutoFixture for DI keeps our tests testing object behavior better than setting up dependencies through the constructor or setters. I think it will suffer the same problems as we're examining private data. It has one benefit in that our public APIs remain pristine from adding in special-ctors/Setters for DI.

But hey, I'm going to play with this and see what happens. Thanks for the code sample!
2012-09-04 15:26 UTC
I have an upcoming article on how to decouple tests from constructor signatures, so stay tuned.
2012-09-04 19:05 UTC
One of the biggest complaints that architects have about TDD is allowing developers to redesign classes to allow for dependency injection. Even without strong change controls from top down, it would be convenient to be able to do DI without having to design for DI. (These cases come up with those doing Test Last rather than Test First/TDD.) Unfortunately this tool chain doesn't help this problem. Power Mock (Java: http://java.dzone.com/articles/using-powermock-mock) reprograms the class loader so this can be done without designing for DI. Perhaps a later release of this tool could as well. As of now, if I have to redesigning for DI[1], I don't need these other things as Moq already gives me this value.

Am I missing something?
==>Lancer---
http://ConfessionsOfAnAgileCoach.blogspot.com


[1]
[code]private readonly Basket basket;
private readonly IPizzaMap map;
public BasketPresenter(Basket basket, IPizzaMap map) // <-- redesign for DI
[/code]
2012-09-18 15:49 UTC

AutoFixture Freeze

Wednesday, 17 March 2010 21:54:53 UTC

One of the important points of AutoFixture is to hide away all the boring details that you don't care about when you are writing a unit test, but that the compiler seems to insist upon. One of these details is how you create a new instance of your SUT.

Every time you create an instance of your SUT using its constructor, you make it more difficult to refactor that constructor. This is particularly true when it comes to Constructor Injection because you often need to define a Test Double in each unit test, but even for primitive types, it's more maintenance-friendly to use a SUT Factory.

AutoFixture is a SUT Factory, so we can use it to create instances of our SUTs. However, how do we correlate constructor parameters with variables in the test when we will not use the constructor directly?

This is where the Freeze method comes in handy, but let's first examine how to do it with the core API methods CreateAnonymous and Register.

Imagine that we want to write a unit test for a Pizza class that takes a name in its constructor and exposes that name as a property. We can write this test like this:

[TestMethod]
public void NameIsCorrect()
{
    // Fixture setup
    var fixture = new Fixture();
 
    var expectedName = fixture.CreateAnonymous("Name");
    fixture.Register(expectedName);
 
    var sut = fixture.CreateAnonymous<Pizza>();
    // Exercise system
    string result = sut.Name;
    // Verify outcome
    Assert.AreEqual(expectedName, result, "Name");
    // Teardown
}

The important lines are these two:

var expectedName = fixture.CreateAnonymous("Name");
fixture.Register(expectedName);

What's going on here is that we create a new string, and then we subsequently Register this string so that every time the fixture instance is asked to create a string, it will return this particular string. This also means that when we ask AutoFixture to create an instance of Pizza, it will use that string as the constructor parameter.

It turned out that we used this coding idiom so much that we decided to encapsulate it in a convenience method. After some debate we arrived at the name Freeze, because we essentially freeze a single anonymous variable in the fixture, bypassing the default algorithm for creating new instances. Incidentally, this is one of very few methods in AutoFixture that breaks CQS, but although that bugs me a little, the Freeze concept has turned out to be so powerful that I live with it.

Here is the same test rewritten to use the Freeze method:

[TestMethod]
public void NameIsCorrect_Freeze()
{
    // Fixture setup
    var fixture = new Fixture();
    var expectedName = fixture.Freeze("Name");
    var sut = fixture.CreateAnonymous<Pizza>();
    // Exercise system
    string result = sut.Name;
    // Verify outcome
    Assert.AreEqual(expectedName, result, "Name");
    // Teardown
}

In this example, we only save a single line of code, but apart from that, the test also becomes a little more communicative because it explicitly calls out that this particular string is frozen.

However, this is still a pretty lame example, but while I intend to follow up with a more complex example, I wanted to introduce the concept gently.

For completeness sake, here's the Pizza class:

public class Pizza
{
    private readonly string name;
 
    public Pizza(string name)
    {
        if (name == null)
        {
            throw new ArgumentNullException("name");
        }
 
        this.name = name;
    }
 
    public string Name
    {
        get { return this.name; }
    }
}

As you can see, the test simply verifies that the constructor parameter is echoed by the Name property, and the Freeze method makes this more explicit while we still enjoy the indirection of not invoking the constructor directly.


Comments

DavidS #
Hi,

I am trying to understand how, in this particular example, AutoFixture makes the set up impervious to changes in the constructor.

Say that for whatever reason the Pizza constructor takes another parameter e.g.

public Pizza(string name, price decimal)

Then surely, we'd have to update the test given. Am I missing something?
2012-12-05 22:51 UTC
The CreateAnonymous method reflects over the constructor to figure out which arguments are required. If you add a decimal to the constructor, it's just going to pick that up and supply an anonymous value of decimal. No update of the test is required.

Try it out :)
2012-12-06 08:45 UTC
DavidS #
Hey Mark,

Thanks for the prompt reply. Now, I think I understand what's going. Effectively, I was not appreciating that the purpose of "Freezing" was to have the string parameter "Name" "frozen" so that the assertion could be made against a known value.

But your explanation has clarified the issue. Thanks very much.
2012-12-06 13:37 UTC
WesM #
I'm curious about how to have different customizations for the same type of object. Example:
new Pizza(string fancyName, string boringName)
2014-03-18 03:46 UTC

WesM, thank you for writing. Perhaps you'll find this article helpful.

2014-03-18 07:33 UTC

CNUG TDD talk

Monday, 08 February 2010 19:15:41 UTC

As part of the Copenhagen .NET User Group (CNUG) winter and early autumn schedule, I'll be giving a talk on (slightly advanced) TDD.

The talk will be in Danish and takes place April 15th, 2010. More details and sign-up here.


Page 68 of 75

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