Rhino Mocks-based auto-mocking with AutoFixture

Saturday, 13 November 2010 21:19:09 UTC

AutoFixture now includes a Rhino Mocks-based auto-mocking feature similar to the Moq-based auto-mocking customization previously described.

The developer of this great optional feature, the talented but discreet Mikkel has this to say:

"The auto-mocking capabilities of AutoFixture now include auto-mocking using Rhino Mocks, completely along the same lines as the existing Moq-extension. Although it will not be a part of the .zip-distribution before the next official release, it can be built from the latest source code (November 13, 2010) which contains the relevant VS2008 solution: AutoRhinoMock.sln. It is built on Rhino.Mocks version 3.6.0.0. To use it, add a reference to Ploeh.AutoFixture.AutoRhinoMock.dll and customize the Fixture instance with:

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

"which automatically will result in mocked instances of requests for interfaces and abstract classes."

I'm really happy to see the AutoFixture eco-system grow in this way, as it both demonstrates how AutoFixture gives you great flexibility and enables you to work with the tools you prefer.


Refactoring from Abstract Factory to Decorator

Monday, 01 November 2010 21:19:06 UTC

Garth Kidd was so nice to point out to me that I hadn't needed stop where I did in my previous post, and he is, of course, correct. Taking a dependency on an Abstract Factory that doesn't take any contextual information (i.e. has no method parameters) is often an indication of a Leaky Abstraction. It indicates that the consumer has knowledge about the dependency's lifetime that it shouldn't have.

We can remove this flaw by introducing a Decorator of the IRepository<T> interface. Something like this should suffice:

public class FoundRepository<T> : IRepository<T>
{
    private readonly IRepository<T> repository;
 
    public FoundRepository(IRepositoryFinder<T> finder)
    {
        if (finder == null)
        {
            throw new ArgumentNullException("finder");
        }
 
        this.repository = finder.FindRepository();
    }
 
    /* Implement IRepository<T> by delegating to
     * this.repository */
}

This means that we can change the implementation of MyServiceOperation to this:

public void MyServiceOperation(
    IRepository<Customer> repository)
{
    // ...
}

This is much better, but this requires a couple of notes.

First of all we should keep in mind that since FoundRepository creates and saves an instance of IRepository right away, we should control the lifetime of FoundRepository. In essense, the lifetime should be tied to the specific service operation. Two concurrent invocations of MyServiceOperation should each receive separate instances of FoundRepository.

Many DI containers support Factory methods, so it may not even be necessary to implement FoundRepository explicitly. Rather, it would be possible to register IRepository<T> so that an instance is always created by invoking IRepositoryFinder<T>.FindRepository().


Comments

Mark, doesn't this contradict the rule to make constructors that get dependencies injected simple? You can't really know what happens inside finder.FindRepository() - it might even access the database...

I am asking, because I have a similar situation:
In the project I am currently refactoring, I created a lot of ConfiguredXYZ decorators that are modeled after this article.
They decorate classes, that have both dependencies and primitive types as ctor parameters. I use the decorator to read these primitive values from the configuration and to create an instance of the decorated class.

Example:


public ConfiguredCache(IConfigService configService, ISomeOtherDependency dep)
{
var expiryTime = configService.Get<DateTime>("ExpiryTimeForCache");
_configuredCache = new ExpiringCache(expiryTime, dep);
}

If IConfigService is implemented to read the database, I will hit the database in the constructor.

What do you think about it? Wouldn't it be better to create the instance of the ExpiringCache only when someone really needs it by invoking a method on ConfiguredCache?
2011-08-10 16:36 UTC
Agreed, but this is just one step in a refactoring process. What I would subsequently tend to do would be to refactor once more and let the Composition Root invoke the factory, which means that the consumer can now take only the result of invoking the factory as a single dependency.

You could also go the other way and perform a lazy evaluation of the dependency, but this is far more complicated to implement because it means that you'd be changing the state of the consumer. This again means that if you want to share the consumer as another dependency, you'll also need to think about thread safety.

In most cases I'd regard lazy evaluation as a premature optimization. As I have explained in another blog post, we shouldn't worry about the cost of composing an object graph.

In your example, IConfigService isn't really a dependency because the ConfiguredCache class doesn't depend on it - it only use it to get an instance of ExpiringCache. Change the constructor by removing the IConfigService and instead require an ExpiringCache (or the interface it implements). Some third party can take care of wiring up the IConfigService for you.

So what if it hits the database? It's probably going to do that sooner or later (meaning, typically, milliseconds or even seconds later) so does it matter? And will it happen often? A cache is only effective if it's shared, which means that we can share it with the Singleton lifetime. If we do that we only need to create the instance once per application, which again means that in the overall picture, that single database hit is insignificant.
2011-08-10 17:45 UTC
Thanks for your response.
Could you write a blog post about that refactoring step you would perform after you refactored to decorators?

I agree with your points in general, but they don't solve the problem that lead to those decorators in the first place:
The configuration of ExpiringCache is complex - not in the sample code, but in the real code. That was the whole reason for introducing those ConfiguredXYZ decorators, because I didn't want to have that complex configuration in the composition root. If you wouldn't create these decorators, how would you do it then? Create an ICache factory that returns a new ExpiringCache? This factory again would need IConfigService and ISomeOtherDependency to work, so from the constructor it would be the same as with the decorator...
And how would you register this factory with the container while reserving auto-wiring? Would you use Autofac's RegisterAdapter to register from ICacheFactory to ICache using the Create method of ICacheFactory?
2011-08-15 13:33 UTC
Why not perform the complex configuration in the Composition Root?
2011-08-15 13:39 UTC
Because I would like to keep it simple.
If I would perform this complex configuration in the Composition Root, it would become a monstrosity, because it would mean to put the other configurations in there, too.
I like my Composition Root "to just work", so I work with conventions. Putting the configurations in there would make this impossible...
2011-08-16 07:26 UTC
Why would it make it impossible?

The code that reads configuration etc. needs to go somewhere. The Composition Root is the correct place because it makes the rest of your application code decoupled from your configuration source(s).

There's nothing that prevents you from expressing conventions around configuration settings as well.
2011-08-16 07:39 UTC
I don't think I understand. If I would put this configuration code inside the composition root it would be several hundred lines long. Maybe even more. I seem to be missing something, because a composition root like this is a maintenance nightmare.
2011-08-16 09:25 UTC
Would the configuration code be longer if you put it in the Composition Root? If that's the case, I can't for the life of me imagine why this would be, so please explain.
2011-08-16 09:39 UTC
No, it wouldn't be longer if I would put it in the Composition Root. That would be very odd, I agree.
But: the configuration code that currently is spread out in several classes would all be in the composition root. Note: "the configuration code" really consists of several classes that are not related to each other. One class configures the SAP object (which SAP server to use, username, password etc.), another configures the cache (see example above), yet another configures the Logger (which file to write to) etc.
It might well be a problem with the architecture per se, because I came to what I have now from an architecture that was centered around a service locator. All the lower levels now are very good, they get dependencies injected and work with them, but I can't figure out, where to put this configuration code.
Because, in my opinion, this configuration code is "domain code". What I mean with this is that it requires special knowledge about the domain it is used in. For example, I don't think that the composition root should need to know about details of an SAP connection, just to configure the SapConnection class... This is more than just reading configuration values and passing them to a constructor. In the SAP example, it reads some values from the database and based on these values it makes some decisions and only after that, the object is created.
Having written it like this, it really sounds as if I should use Abstract Factories, but you objected to them in one of your earlier answers, which confuses me :-)
2011-08-16 10:05 UTC
The Composition Root doesn't have to be a single class. It's an architectural concept. It can have as many classes as you need as long as the stay together. Usually we implement the Composition Root in the same project as the application's entry point. This is where we wire everything together, so this particular place tends to not be (unit) testable. As such, we should go to great lengths to ensure that the entry point is a Humble Executable.

Thus it follows that the Composition Root can be as large as necessary, but it must contain no logic. My personal rule of thumb is that all members must have a cyclomatic complexity of 1.

Configuration isn't logic, but you may have application logic that depends on configuration values, so the trick is to separate the logic from the source of the values. The logic goes elsewhere, but the values are being dehydrated (or otherwise initialized) by the Composition Root.

I would consider a SAP connection an infrastructure concern. If you base your domain logic on knowledge of infrastructure specifics you're making life hard for yourself.
2011-08-16 10:40 UTC

Refactoring from Service Locator to Abstract Factory

Monday, 01 November 2010 19:43:24 UTC

One of the readers of my book recently asked me an interesting question that relates to the disadvantages of the Service Locator anti-pattern. I found both the question and the potential solution so interesting that I would like to share it.

In short, the reader's organization currently uses Service Locator in their code, but don't really see a way out of it. This post demonstrates how we can refactor from Service Locator to Abstract Factory. Here's the original question:

"We have been writing a WCF middle tier using DI

"Our application talks to multiple databases.  There is one Global database which contains Enterprise records, and each Enterprise has the connection string of a corresponding Enterprise database.

"The trick is when we want to write a service which connects to an Enterprise database.  The context for which enterprise we are dealing with is not available until one of the service methods is called, so what we do is this:

public void MyServiceOperation(
    EnterpriseContext context)
{
   
/* Get a Customer repository operating
        * in the given enterprise's context
        * (database) */

    var customerRepository =
        context.FindRepository<Customer>(
            context.EnterpriseId);
    // ...
}

"I'm not sure how, in this case, we can turn what we've got into a more pure DI system, since we have the dependency on the EnterpriseContext passed in to each service method.  We are mocking and testing just fine, and seem reasonably well decoupled.  Any ideas?"

When we look at the FindRepository method we quickly find that it's a Service Locator. There are many problems with Service Locator, but the general issue is that the generic argument can be one of an unbounded set of types.

The problem is that seen from the outside, the consuming type (MyService in the example) doesn't advertise its dependencies. In the example the dependency is a CustomerRepository, but you could later go into the implementation of MyServiceOperation and change the call to context.FindRepository<Qux>(context.EnterpriseId) and everything would still compile. However, at run-time, you'd likely get an exception.

It would be much safer to use an Abstract Factory, but how do we get there from here, and will it be better?

Let's see how we can do that. First, we'll have to make some assumptions on how EnterpriseContext works. In the following, I'll assume that it looks like this - warning: it's ugly, but that's the point, so don't give up reading just yet:

public class EnterpriseContext
{
    private readonly int enterpriseId;
    private readonly IDictionary<int, string>
        connectionStrings;

    public EnterpriseContext(int enterpriseId)
    {
        this.enterpriseId = enterpriseId;

        this.connectionStrings =
            new Dictionary<int, string>();
        this.connectionStrings[1] = "Foo";
        this.connectionStrings[2] = "Bar";
        this.connectionStrings[3] = "Baz";
    }

    public virtual int EnterpriseId
    {
        get { return this.enterpriseId; }
    }

    public virtual IRepository<T> FindRepository<T>(
        int enterpriseId)
    {
        if (typeof(T) == typeof(Customer))
        {
            return (IRepository<T>)this
                .FindCustomerRepository(enterpriseId);
        }
        if (typeof(T) == typeof(Campaign))
        {
            return (IRepository<T>)this
                .FindCampaignRepository(enterpriseId);
        }
        if (typeof(T) == typeof(Product))
        {
            return (IRepository<T>)this
                .FindProductRepository(enterpriseId);
        }

        throw new InvalidOperationException("...");
    }

    private IRepository<Campaign>
        FindCampaignRepository(int enterpriseId)
    {
        var cs = this.connectionStrings[enterpriseId];
        return new CampaignRepository(cs);
    }

    private IRepository<Customer>
        FindCustomerRepository(int enterpriseId)
    {
        var cs = this.connectionStrings[enterpriseId];
        return new CustomerRepository(cs);
    }

    private IRepository<Product>
        FindProductRepository(int enterpriseId)
    {
        var cs = this.connectionStrings[enterpriseId];
        return new ProductRepository(cs);
    }
}

That's pretty horrible, but that's exactly the point. Every time we need to add a new type of repository, we'll need to modify this class, so it's one big violation of the Open/Closed Principle.

I didn't implement EnterpriseContext with a DI Container on purpose. Yes: using a DI Container would make it appear less ugly, but it would only hide the design issue - not address it. I chose the above implementation to demonstrate just how ugly this sort of design really is.

So, let's start refactoring.

Step 1 #

We change each of the private finder methods to public methods.

In this example, there are only three methods, but I realize that in a real system there might be many more. However, we'll end up with only a single interface and its implementation, so don't despair just yet. It'll turn out just fine.

As a single example the FindCustomerRepository method is shown here:

public IRepository<Customer>
    FindCustomerRepository(int enterpriseId)
{
    var cs = this.connectionStrings[enterpriseId];
    return new CustomerRepository(cs);
}

For each of the methods we extract an interface, like this:

public interface ICustomerRepositoryFinder
{
    int EnterpriseId { get; }

    IRepository<Customer> FindCustomerRepository(
        int enterpriseId);
}

We also include the EnterpriseId property because we'll need it soon. This is just an intermediary artifact which is not going to survive until the end.

This is very reminiscent of the steps described by Udi Dahan in his excellent talk Intentions & Interfaces: Making patterns concrete. We make the roles of finding repositories explicit.

This leaves us with three distinct interfaces that EnterpriseContext can implement:

public class EnterpriseContext : 
    ICampaignRepositoryFinder,
    ICustomerRepositoryFinder,
    IProductRepositoryFinder

Until now, we haven't touched the service.

Step 2 #

We can now change the implementation of MyServiceOperation to explicitly require only the role that it needs:

public void MyServiceOperation(
    ICustomerRepositoryFinder finder)
{
    var customerRepository =
        finder.FindCustomerRepository(
            finder.EnterpriseId);
}

Since we now only consume the strongly typed role interfaces, we can now delete the original FindRepository<T> method from EnterpriseContext.

Step 3 #

At this point, we're actually already done, since ICustomerRepositoryFinder is an Abstract Factory, but we can make the API even better. When we consider the implementation of MyServiceOperation, it should quickly become clear that there's a sort of local Feature Envy in play. Why do we need to access finder.EnterpriseId to invoke finder.FindCustomerRepository? Shouldn't it rather be the finder's own responsibility to figure that out for us?

Instead, let us change the implementation so that the method does not need the enterpriseId parameter:

public IRepository<Customer> FindCustomerRepository()
{
    var cs =
        this.connectionStrings[this.EnterpriseId];
    return new CustomerRepository(cs);
}

Notice that the EnterpriseId can be accessed just as well from the implementation of the method itself. This change requires us to also change the interface:

public interface ICustomerRepositoryFinder
{
    IRepository<Customer> FindCustomerRepository();
}

Notice that we removed the EnterpriseId property, as well as the enterpriseId parameter. The fact that there's an enterprise ID in play is now an implementation detail.

MyServiceOperation now looks like this:

public void MyServiceOperation(
    ICustomerRepositoryFinder finder)
{
    var customerRepository =
        finder.FindCustomerRepository();
}

This takes care of the Feature Envy smell, but still leaves us with a lot of very similarly looking interfaces: ICampaignRepositoryFinder, ICustomerRepositoryFinder and IProductRepositoryFinder.

Step 4 #

We can collapse all the very similar interfaces into a single generic interface:

public interface IRepositoryFinder<T>
{
    IRepository<T> FindRepository();
}

With that, MyServiceOperation now becomes:

public void MyServiceOperation(
    IRepositoryFinder<Customer> finder)
{
    var customerRepository =
        finder.FindRepository();
}

Now that we only have a single generic interface (which is still an Abstract Factory), we can seriously consider getting rid of all the very similarly looking implementations in EnterpriseContext and instead just create a single generic class. We now have a more explicit API that better communicates intent.

How is this better? What if a method needs both an IRepository<Customer> and an IRepository<Product>? We'll now have to pass two parameters instead of one.

Yes, but that's good because it explicitly calls to your attention exactly which collaborators are involved. With the original Service Locator, you might not notice the responsibility creep as you over time request more and more repositories from the EnterpriseContext. With Abstract Factories in play, violations of the Single Responsibility Principle (SRP) becomes much more obvious.

Refactoring from Service Locator to Abstract Factories make it more painful to violate the SRP.

You can always make roles explicit to get rid of Service Locators. This is likely to result in a more explicit design where doing the right thing feels more natural than doing the wrong thing.


Pattern Recognition: Abstract Factory or Service Locator?

Monday, 01 November 2010 12:31:53 UTC

It's easy to confuse the Abstract Factory pattern with the Service Locator anti-pattern - particularly so when generics or contextual information is involved. However, it's really easy to distinguish between there two, and here's how!

Here are both (anti-)patterns in condensed form opposite each other:

Abstract Factory Service Locator
public interface IFactory<T>
{
    T Create(object context);
}
public interface IServiceLocator
{
    T Create<T>(object context);
}

For these examples I chose to demonstrate both as generic interfaces that take some kind of contextual information (context) as input.

In this example the context can be any object, but we could also have considered a more strongly typed context parameter. Other variations include more than one method parameter, or, in the degenerate case, no parameters at all.

Both interfaces have a simple Create method that returns the generic type T, so it's easy to confuse the two. However, even for generic types, it's easy to tell one from the other:

An Abstract Factory is a generic type, and the return type of the Create method is determined by the type of the factory itself. In other words, a constructed type can only return instances of a single type.

A Service Locator, on the other hand, is a non-generic interface with a generic method. The Create method of a single Service Locator can return instances of an infinite number of types.

Even simpler:

An Abstract Factory is a generic type with a non-generic Create method; a Service Locator is a non-generic type with a generic Create method.

The name of the method, the number of parameters, and other circumstances may vary. The types may not be generic, or may be base classes instead of interfaces, but at the heart of it, the question is whether you can ask for an arbitrary type from the service, or only a single, static type.


Comments

mmm... i generally agree and it's an easy way to create a simple rule set for those learning the patterns. but i'm having a hard time with this one for a couple of reasons.

1) i've always viewed an IoC container (whether it's used for dependency injection or service location) as an amalgamation of design pattern, including the abstract factory (along with builders, registries, and others)

2) a design pattern is not always identified by implementation detail, but by intent. take a look at the Decorator and Proxy design patterns as implemented in C#, for example. There are, quite often and in the most basic of implementations, very few differences between these two patterns when it comes down to the implementation. the real difference is the intent of use

i don't think you are necessarily wrong in what you've said. i do think there's much more room for a gray area in between these two patterns, though. a service locator is an abstract factory (along with many other things), and an abstract factory can be used as a service locator. so, while the two patterns are distinct in their intent, they are often blurred and indistinguishable in implementation.
2010-11-01 13:08 UTC
Good point about design patterns not always being identifiable by implementation details. That's not quite what I said, either... We can distinguish between the two from differences in the structure of their public APIs. That's not the implementation, but rather the shape, of the type. Still, point taken.

However, the whole point is that there are fundamental differences between Abstract Factory and Service Locator. One is good, the other is evil. Learning to tell them apart is important.
2010-11-01 20:23 UTC
"An Abstract Factory is a generic type with a non-generic Create method"
is it? looks to me like the Create method IS generic, it just so happens to have a constraint
2010-11-14 04:08 UTC
True, but I'm sure you understand what is meant :)
2010-11-14 08:10 UTC

Convention-based Customizations with AutoFixture

Tuesday, 19 October 2010 19:46:53 UTC

As previous posts have described, AutoFixture creates Anonymous Variables based on the notion of being able to always hit within a well-behaved Equivalence Class for a given type. This works well a lot of the time because AutoFixture has some sensible defaults: numbers are positive integers and strings are GUIDs.

This last part only works as long as strings are nothing but opaque blobs to the consuming class. This is, however, not an unreasonable assumption. Consider classes that implement Entities such as Person or Address. Strings will often take the form of FirstName, LastName, Street, etc. In all such cases, the value of the string usually doesn't matter.

However, there will always be cases where the value of a string has a special meaning of its own. It will often be best to let AutoFixture guide us towards a better API design, but this is not always possible. Sometimes there are rules that constrain the formatting of a string.

As an example, consider a Money class with this constructor:

public Money(decimal amount, string currencyCode)
{
    if (currencyCode == null)
    {
        throw new ArgumentNullException("...");
    }
    if (!CurrencyCodes.IsValid(currencyCode))
    {
        throw new ArgumentException("...");
    }

    this.amount = amount;
    this.currencyCode = currencyCode;
}

Notice that the constructor only allows properly formatted currency codes (such as e.g. “DKK”, “USD”, “AUD”, etc.) through, while other strings will throw an exception. AutoFixture's default behavior of creating GUIDs as strings is problematic, as the Money constructor will throw on a GUID.

We could attempt to fix this by changing the way AutoFixture generates strings in general, but that may not be the best solution as it may interfere with other string values. It is, however, easy to do:

fixture.Inject("DKK");

This simply injects the “DKK” string into the fixture, causing all subsequent strings to have the same value. However, a hypothetical Pizza class with Name and Description properties in addition to a Price property of type Money will now look like this:

{
  "Name": "DKK",
  "Price": {
    "Amount": 1.0,
    "CurrencyCode": "DKK"
  },
  "Description": "DKK"
}

What we really want is to customize only the currency code. This is where the extremely customizable architecture of AutoFixture can help us. As the documentation explains, lots of different request will flow through the kernel's Chain of Responsibility to create a Money instance. To populate the two parameters of the Money constructor, two ParameterInfo requests will be issued - one for each parameter. We can take advantage of this to create a custom ISpecimenBuilder that only addresses string parameters with the name currencyCode.

public class CurrencyCodeSpecimenBuilder : 
    ISpecimenBuilder
{
    public object Create(object request,
        ISpecimenContext context)
    {
        var pi = request as ParameterInfo;
        if (pi == null)
        {
            return new NoSpecimen(request);
        }
        if (pi.ParameterType != typeof(string)
            || pi.Name != "currencyCode")
        {
            return new NoSpecimen(request);
        }

        return "DKK";
    }
}

It simply examines the request to determine whether this is something that it should address at all. Only if the request is a ParameterInfo representing a string parameter named currencyCode do we deal with it. In any other case we return NoSpecimen, which simply tells AutoFixture that it should ask another ISpecimenBuilder instead.

Here we just return the hard-coded string “DKK”, but we could easily have expanded the example to use a more varied generation algorithm. I will leave that, as well as how to generalize this in other ways, as exercises to the reader.

With CurrencyCodeSpecimenBuilder available, we can add it to the Fixture like this:

fixture.Customizations.Add(
    new CurrencyCodeSpecimenBuilder());

With this customization added, a Pizza instance now looks like this:

{
  "Name": "namec6b7a923-ea78-4817-9e24-a6863a597645",
  "Price": {
    "Amount": 1.0,
    "CurrencyCode": "DKK"
  },
  "Description": "Description63ef17d7-876d-46d8-af73-1ed91f83e699"
}

Notice how only the currency code is affected while all other string values are created by the default algorithm.

In a nutshell, a custom ISpecimenBuilder can be used to implement all sorts of custom conventions for AutoFixture. The one shown here applies the string “DKK” to all string parameters named currencyCode. This mean that the convention isn't necessarily constrained to the Money constructor, but applies to all ParamterInfo instances that fit the specification.


Comments

I know this post is a couple of years old, and maybe AutoFixture has changed since it was written. However, in the above example for the CurrencyCodeSpecimenBuilder, it shows testing the request object to see if it is a ParameterInfo. This never worked when I tried to use it, however changing ParameterInfo to PropertyInfo and pi.ParameterType to pi.PropertyType fixed it for me (meaning that it actually hit found the property I was attempting to match). I'm just mentioning this in case it is useful to someone else who stumbles across this blog post.

Thanks
2012-11-28 20:28 UTC
Jon, thanks for your comment.

The reason why the CurrencyCodeSpecimenBuilder is looking for a ParameterInfo instance is because the thing it's looking for is exactly the constructor parameter to the Money class.

If you instead want to match on a property, PropertyInfo is indeed the correct request to look for.

(and FieldInfo is used if you want to match on a public field...)
2012-11-28 20:36 UTC
WesM
What kinds of things can a "request" be?
2014-03-18 04:28 UTC

A request can be anything, but will often by a Type, ParameterInfo, or PropertyInfo.

2014-03-18 18:08 UTC
WesM
How would I get a new fixturized object from within a specimen builder? Like Fixture.Create().ToUniversalTime() or some other customization based on your current implementation of random values.
2014-03-21 10:38 UTC

You can use the context argument passed to the Create method to resolve other values; you only need to watch out for infinite recursions: you can't ask for an unconditional string if the Specimen Builder you're writing handles unconditional strings.

2014-03-22 8:41 UTC
Jeff Soper

I've written several custom ISpecimenBuilder implementations similar to your example above, and I always wince when testing for the ParameterType.Name value (i.e., if(pi.Name == "myParamName"){...}). It seems like it makes a test that would use this implementation very brittle - no longer would I have freedom to change the name of the paramter to suit my asthetics, without relying on a refactoring tool (cough, cough, Resharper, cough, cough) to hopefully pickup on the string value in my test suite and prompt me to change it there as well.

This makes me think that I shouldn't need to be doing this, and that a design refactoring of my SUT would be a better option. Care to comment on this observation? Is there a common scenario/design trap that illustrates a better way? Or am I already in dangerous design territory based on my need to create an ISpecimenBuilder in the first place?

2014-04-30 19:38 UTC

Jeff, thank you for writing. Your question warranted a new blog post; it may not answer all of your concerns, but hopefully some of them. Read it and let me know if you still have questions.

2014-05-02 8:23 UTC

Windows Azure Migration Sanity Check

Thursday, 14 October 2010 11:08:27 UTC

Recently I attended a workshop where we attempted to migrate an existing web application to Windows Azure. It was a worthwhile workshop that left me with a few key takeaways related to migrating applications to Windows Azure.

The first and most important point is so self-evident that I seriously considered not publishing it. However, apparently it wasn't self-evident to all workshop participants, so someone else might also benefit from this general advice:

Before migrating to Windows Azure, make sure that the application scales to at least two normal servers.

It's as simple as that - still, lots of web developers never consider this aspect of application architecture.

Why is this important in relation to Azure? The Windows Azure SLA only applies if you deploy two or more instances, which makes sense since the hosting servers occasionally need to be patched etc.

Unless you don't care about the SLA, your application must be able to ‘scale' to at least two servers. If it can't, fix this issue first, before attempting to migrate to Windows Azure. You can test this locally by simply installing your application on two different servers and put them behind a load balancer (you can use virtual machines if you don't have the hardware). Only if it works consistently in this configuration should you consider deploying to Azure.

Here are the most common issues that may prevent the application from ‘scaling':

  • Keeping state in memory. If you must use session state, use one of the out-of-process session state store providers.
  • Using the file system for persistent storage. The file system is local to each server.

Making sure that the application ‘scales' to at least two servers is such a simple sanity check that it should go without saying, but apparently it doesn't.

Please note that I put ‘scaling' in quotes here. An application that runs on only two servers has yet to prove that it's truly scalable, but that's another story.

Also note that this sanity check in no way guarantees that the application will run on Azure. However, if the check fails, it most likely will not.


Comments

Thomas
Hello Mark,

I would also add somme CCC like cash. you may consider to move from a local cache to distributed one to save some unwanted behaviour.

2010-10-17 20:25 UTC

AutoFixture 2.0 Released

Sunday, 10 October 2010 18:42:33 UTC

It gives me great pleasure to announce the release of AutoFixture 2.0. This release fixes a few minor issues since beta 1, but apart from that there are no significant changes.

This is a major release compared to AutoFixture 1.1, featuring a completely new kernel, as well as new features and extensibility points. The beta 1 announcement sums up the changes. Get it here.


AutoData Theories with AutoFixture

Friday, 08 October 2010 08:48:07 UTC

AutoFixture 2.0 comes with a new extension for xUnit.net data theories. For those of us using xUnit.net, it can help make our unit tests more succinct and declarative.

AutoFixture's support for xUnit.net is implemented in a separate assembly. AutoFixture itself has no dependency on xUnit.net, and if you use another unit testing framework, you can just ignore the existence of the Ploeh.AutoFixture.Xunit assembly.

Let's go back and revisit the previous test we wrote using AutoFixture and its auto-mocking extension:

[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 how all of the Fixture Setup phase is only used to create various objects that will be used in the test. First we create the fixture object, and then we use it to create four other objects. That turns out to be a pretty common idiom when using AutoFixture, so it's worthwhile to reduce the clutter if possible.

With xUnit.net's excellent extensibility features, we can. AutoFixture 2.0 now includes the AutoDataAttribute in a separate assembly. AutoDataAttribute derives from xUnit.net's DataAttribute (just like InlineDataAttribute), and while we can use it as is, it becomes really powerful if we combine it with auto-mocking like this:

public class AutoMoqDataAttribute : AutoDataAttribute
{
    public AutoMoqDataAttribute()
        : base(new Fixture()
            .Customize(new AutoMoqCustomization()))
    {
    }
}

This is a custom attribute that combines AutoFixture's two optional extensions for auto-mocking and xUnit.net support. With the AutoMoqDataAttribute in place, we can now rewrite the above test like this:

[Theory, AutoMoqData]
public void AddWillPipeMapCorrectly([Frozen]Basket basket,
    [Frozen]Mock<IPizzaMap> mapMock, PizzaPresenter pizza,
    BasketPresenter sut)
{
    // Fixture setup
    // Exercise system
    sut.Add(pizza);
    // Verify outcome
    mapMock.Verify(m => m.Pipe(pizza, basket.Add));
    // Teardown
}

The AutoDataAttribute simply uses a Fixture object to create the objects declared in the unit tests parameter list. Notice that the test is no longer a [Fact], but rather a [Theory].

The only slightly tricky thing to notice is that when we declare a parameter object, it will automatically map to a call to the CreateAnonymous method for the parameter type. However, when we need to invoke the Freeze method, we can add the [Frozen] attribute in front of the parameter.

The best part about data theories is that they don't prevent us from writing normal unit tests in the same Test Class, and this carries over to the [AutoData] attribute. We can use it when it's possible, but for those more complex tests where we need to interact with a Fixture instance, we can still write a normal [Fact].


Comments

I'm poking around at the AutoDataAttribute and I might be missing something but in a simple test I'm getting an InvalidOperationException:

System.InvalidOperationException : No data found for XunitSample.TestClass.TestMethod2
System.InvalidOperationException : No data found for XunitSample.TestClass.TestMethod1

Did I miss something in terms of setup? Sample code here - https://gist.github.com/1920943
2012-02-27 02:49 UTC
I just copied in the code from your gist and added the appropriate NuGet packages, followed by an Add-BindingRedirect, and everything works as intended. In other words, I can't reproduce the problem based on the information given here. I'd love to help, but I don't think this is the correct forum. Could you ask on Stack Overflow instead? If so, I'll take a look.
2012-02-27 06:57 UTC
Brian McCord
I am very impressed with this way of doing things, but I have one question. If you need to do setup on a mock to force certain return values, are you forced to go back to using a Fact and setting up the mock manually?
2012-03-02 17:00 UTC
Absolutely, that's what the [Frozen] attribute is for. Here's an example (second test).
2012-03-03 19:42 UTC
Jeff Soper

Forgive me if I missed this point in your blog, but it seems that the parameter order is critical when injecting objects marked with the [Frozen] attribute into your test, if the SUT is being injected with that frozen object.

I was refactoring my tests to make use of AutoData like you've shown here, and was adding my [Frozen]Mock<IMySutDependency> parameter willy-nilly to the end of the test parameters, *after* the SUT parameter. I was freezing it so that I could verify the same mocked dependency that was injected into the SUT as part of my test, or so I thought...

void MySutTest(MySut sut, [Frozen]Mock<IMySutDependency> frozen)

After a brief episode of confusion and self-loathing, I moved the frozen mocked dependency in front of the SUT in the test parameter list. Skies parted, angels sang, test passed again.

void MySutTest([Frozen]Mock<IMySutDependency> frozen, MySut sut)

2013-08-22 23:00 UTC

Jeff, thank you for your comment. As you have discovered, the order of test parameters matter when you apply those 'hint' attributes, like [Frozen]. This is by design, because it enables you to generate one or more unique values of a data type before you freeze it. This could sometimes be important, although it's not something I do a lot. Keep in mind that the [Frozen] attribute wasn't designed exclusively with mocks in mind; it doesn't know anything about mocks - it just freeze a Type.

In general, all of those 'hint' attributes apply an ICustomization, and they apply each ICustomization in the order of the arguments to which they are applied. The order of AutoFixture Customizations matter.

2013-08-24 12:39 UTC

The Register Resolve Release pattern

Wednesday, 29 September 2010 11:50:02 UTC

The subject of Dependency Injection (DI) in general, and DI Containers specifically, suffers from horrible terminology that seems to confuse a lot of people. Newcomers to DI often think about DI Containers as a sort of Abstract Factory on steroids. It's not. Nicholas Blumhardt already realized and described this phenomenon a couple of years ago.

The core of the matter is that as developers, we are extremely accustomed to thinking about components and services in terms of queries instead of commands. However, the Hollywood Principle insists that we should embrace a tell, don't ask philosophy. We can apply this principles to DI Containers as well: Don't call the container; it'l call you.

This leads us to what Krzysztof Koźmic calls the three calls pattern. Basically it states that we should only do three things with a DI Container:

  1. Bootstrap the container
  2. Resolve root components
  3. Dispose this container

This is very sound advice and independently of Krzysztof I've been doing something similar for years - so perhaps the pattern label is actually in order here.

However, I think that the pattern deserves a more catchy name, so in the spirit of the Arrange Act Assert (AAA) pattern for unit testing I propose that we name it the Register Resolve Release (RRR) pattern. The names originate with Castle Windsor terminology, where we:

  1. Register components with the container
  2. Resolve root components
  3. Release components from the container

Other containers also support the RRR pattern, but if we were to pick their terminology, it would rather be the Configure GetInstance Dispose (CGD) pattern (or something similar), and that's just not as catchy.

We can rewrite a previous example with Castle Windsor and annotate it with comments to call out where the three container phases occur:

private static void Main(string[] args)
{
    var container = new WindsorContainer();
    container.Kernel.Resolver.AddSubResolver(
        new CollectionResolver(container.Kernel));
 
    // Register
    container.Register(
        Component.For<IParser>()
            .ImplementedBy<WineInformationParser>(),
        Component.For<IParser>()
            .ImplementedBy<HelpParser>(),
        Component.For<IParseService>()
            .ImplementedBy<CoalescingParserSelector>(),
        Component.For<IWineRepository>()
            .ImplementedBy<SqlWineRepository>(),
        Component.For<IMessageWriter>()
            .ImplementedBy<ConsoleMessageWriter>());
 
    // Resolve
    var ps = container.Resolve<IParseService>();
    ps.Parse(args).CreateCommand().Execute();
 
    // Release
    container.Release(ps);
    container.Dispose();
}

Notice that in most cases, explicitly invoking the Release method isn't necessary, but I included it here to make the pattern stand out.

So there it is: the Register Resolve Release pattern.


Comments

Harry Dev
I agree completely and think the Register Resolve Release (RRR) moniker is very good. You should think about creating a wikipedia or c2 entry for it to promote it ;)
2010-09-29 12:21 UTC
Nice coinage, gets a vote from me.
2010-10-03 21:28 UTC
Arnis L.
This realization took me few months. It truly is quite hard for newcomers.
2010-10-03 22:42 UTC
You could use a using block, too.
2010-10-07 17:03 UTC
Yes, although the general pattern is a bit more subtle than this. In the example given, the call to the Release method is largely redundant. If we assume that this is the case, a using block disposes the container as well.

However, a using block invokes Dispose, but not Release. Releasing an object graph is conceptually very different from disposing the container. However, in the degenerate case shown here, there's not a lot of difference, but in a server scenario where we use the container to resolve an object graph per request, we resolve and release many object graphs all the time. In such scenarios we only dispose the container when the application itself recycles, and even then, we may never be given notice that this happens.
2010-10-07 21:09 UTC
Great name, I like it. RRR is easy to remember and makes sense to me perfectly. Thanks.
2012-06-09 06:45 UTC

Instrumentation with Decorators and Interceptors

Monday, 20 September 2010 19:18:21 UTC

One of my readers recently asked me an interesting question. It relates to my book's chapter about Interception (chapter 9) and Decorators and how they can be used for instrumentation-like purposes.

In an earlier blog post we saw how we can use Decorators to implement Cross-Cutting Concerns, but the question relates to how a set of Decorators can be used to log additional information about code execution, such as the time before and after a method is called, the name of the method and so on.

A Decorator can excellently address such a concern as well, as we will see here. Let us first define an IRegistrar interface and create an implementation like this:

public class ConsoleRegistrar : IRegistrar
{
    public void Register(Guid id, string text)
    {
        var now = DateTimeOffset.Now;
        Console.WriteLine("{0}\t{1:s}.{2}\t{3}",
            id, now, now.Millisecond, text);
    }
}

Although this implementation ‘logs' to the Console, I'm sure you can imagine other implementations. The point is that given this interface, we can add all sorts of ambient information such as the thread ID, the name of the current principal, the current culture and whatnot, while the text string variable still gives us an option to log more information. If we want a more detailed API, we can just make it more detailed - after all, the IRegistrar interface is just an example.

We now know how to register events, but are seemingly no nearer to instrumenting an application. How do we do that? Let us see how we can instrument the OrderProcessor class that I have described several times in past posts.

At the place I left off, the OrderProcessor class uses Constructor Injection all the way down. Although I would normally prefer using a DI Container to auto-wire it, here's a manual composition using Pure DI just to remind you of the general structure of the class and its dependencies:

var sut = new OrderProcessor(
    new OrderValidator(), 
    new OrderShipper(),
    new OrderCollector(
        new AccountsReceivable(),
        new RateExchange(),
        new UserContext()));

All the dependencies injected into the OrderProcessor instance implement interfaces on which OrderProcessor relies. This means that we can decorate each concrete dependency with an implementation that instruments it.

Here's an example that instruments the IOrderProcessor interface itself:

public class InstrumentedOrderProcessor : IOrderProcessor
{
    private readonly IOrderProcessor orderProcessor;
    private readonly IRegistrar registrar;
 
    public InstrumentedOrderProcessor(
        IOrderProcessor processor,
        IRegistrar registrar)
    {
        if (processor == null)
        {
            throw new ArgumentNullException("processor");
        }
        if (registrar == null)
        {
            throw new ArgumentNullException("registrar");
        }
 
        this.orderProcessor = processor;
        this.registrar = registrar;
    }
 
    #region IOrderProcessor Members
 
    public SuccessResult Process(Order order)
    {
        var correlationId = Guid.NewGuid();
        this.registrar.Register(correlationId,
            string.Format("Process begins ({0})",
                this.orderProcessor.GetType().Name));
 
        var result = this.orderProcessor.Process(order);
 
        this.registrar.Register(correlationId,
            string.Format("Process ends   ({0})", 
            this.orderProcessor.GetType().Name));
 
        return result;
    }
 
    #endregion
}

That looks like quite a mouthful, but it's really quite simple - the cyclomatic complexity of the Process method is as low as it can be: 1. We really just register the Process method call before and after invoking the decorated IOrderProcessor.

Without changing anything else than the composition itself, we can now instrument the IOrderProcessor interface:

var registrar = new ConsoleRegistrar();
var sut = new InstrumentedOrderProcessor(
    new OrderProcessor(
        new OrderValidator(),
        new OrderShipper(),
        new OrderCollector(
            new AccountsReceivable(),
            new RateExchange(),
            new UserContext())),
    registrar);

However, imagine implementing an InstrumentedXyz for every IXyz and compose the application with them. It's possible, but it's going to get old really fast - not to mention that it massively violates the DRY principle.

Fortunately we can solve this issue with any DI Container that supports dynamic interception. Castle Windsor does, so let's see how that could work.

Instead of implementing the same code ‘template' over and over again to instrument an interface, we can do it once and for all with an interceptor. Imagine that we delete the InstrumentedOrderProcessor; instead, we create this:

public class InstrumentingInterceptor : IInterceptor
{
    private readonly IRegistrar registrar;
 
    public InstrumentingInterceptor(IRegistrar registrar)
    {
        if (registrar == null)
        {
            throw new ArgumentNullException("registrar");
        }
 
        this.registrar = registrar;
    }
 
    #region IInterceptor Members
 
    public void Intercept(IInvocation invocation)
    {
        var correlationId = Guid.NewGuid();
        this.registrar.Register(correlationId, 
            string.Format("{0} begins ({1})", 
                invocation.Method.Name,
                invocation.TargetType.Name));
 
        invocation.Proceed();
 
        this.registrar.Register(correlationId,
            string.Format("{0} ends   ({1})", 
                invocation.Method.Name, 
                invocation.TargetType.Name));
    }
 
    #endregion
}

If you compare this to the Process method of InstrumentedOrderProcessor (that we don't need anymore), you should be able to see that they are very similar. In this version, we just use the invocation argument to retrieve information about the decorated method.

We can now add InstrumentingInterceptor to a WindsorContainer and enable it for all appropriate components. When we do that and invoke the Process method on the resolved IOrderProcessor, we get a result like this:

bbb9724e-0fad-4b06-9bb0-b8c1c460cded    2010-09-20T21:01:16.744    Process begins (OrderProcessor)
43349d42-a463-463b-8ddf-e569e3170c97    2010-09-20T21:01:16.745    Validate begins (TrueOrderValidator)
43349d42-a463-463b-8ddf-e569e3170c97    2010-09-20T21:01:16.745    Validate ends   (TrueOrderValidator)
44fdccc8-f12d-4057-ae03-791225686504    2010-09-20T21:01:16.746    Collect begins (OrderCollector)
8bbb1a0c-6134-4652-a4af-cd8c0c7184a0    2010-09-20T21:01:16.746    GetCurrentUser begins (UserContext)
8bbb1a0c-6134-4652-a4af-cd8c0c7184a0    2010-09-20T21:01:16.747    GetCurrentUser ends   (UserContext)
d54359ff-8c32-487f-8728-b19ff0bf4942    2010-09-20T21:01:16.747    GetCurrentUser begins (UserContext)
d54359ff-8c32-487f-8728-b19ff0bf4942    2010-09-20T21:01:16.747    GetCurrentUser ends   (UserContext)
c54c4506-23a8-4553-ba9a-066fc64252d2    2010-09-20T21:01:16.748    GetSelectedCurrency begins (UserContext)
c54c4506-23a8-4553-ba9a-066fc64252d2    2010-09-20T21:01:16.748    GetSelectedCurrency ends   (UserContext)
b3dba76b-6b4e-44fa-aca5-52b2d8509db3    2010-09-20T21:01:16.750    Convert begins (RateExchange)
b3dba76b-6b4e-44fa-aca5-52b2d8509db3    2010-09-20T21:01:16.751    Convert ends   (RateExchange)
e07765bd-fe07-4486-96f1-f74d77241343    2010-09-20T21:01:16.751    Collect begins (AccountsReceivable)
e07765bd-fe07-4486-96f1-f74d77241343    2010-09-20T21:01:16.752    Collect ends   (AccountsReceivable)
44fdccc8-f12d-4057-ae03-791225686504    2010-09-20T21:01:16.752    Collect ends   (OrderCollector)
231055d3-4ebb-425d-8d69-fb9c85d9a860    2010-09-20T21:01:16.752    Ship begins (OrderShipper)
231055d3-4ebb-425d-8d69-fb9c85d9a860    2010-09-20T21:01:16.753    Ship ends   (OrderShipper)
bbb9724e-0fad-4b06-9bb0-b8c1c460cded    2010-09-20T21:01:16.753    Process ends   (OrderProcessor)

Notice how we care easily see where and when method calls begin and end using the descriptive text as well as the correlation id. I will leave it as an exercise for the reader to come up with an API that provides better parsing options etc.

As a final note it's worth pointing out that this way of instrumenting an application (or part of it) can be done following the Open/Closed Principle. I never changed the original implementation of any of the components.


Page 40 of 50

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