# Wednesday, August 25, 2010

One of my Twitter followers who appears to be using AutoFixture recently asked me this:

So with the AutoMoqCustomization I feel like I should get Mocks with concrete types too (except the sut) - why am I wrong?

AutoFixture’s extention for auto-mocking with Moq was never meant as a general modification of behavior. Customizations extend the behavior of AutoFixture; they don’t change it. There’s a subtle difference. In any case, the auto-mocking customization was always meant as a fallback mechanism that would create Mocks for interfaces and abstract types because AutoFixture doesn’t know how to deal with those.

Apparently @ZeroBugBounce also want concrete classes to be issued as Mock instances, which is not quite the same thing; AutoFixture already has a strategy for that (it’s called ConstructorInvoker).

Nevertheless I decided to spike a little on this to see if I could get it working. It turns out I needed to open some of the auto-mocking classes a bit for extensibility (always a good thing), so the following doesn’t work with AutoFixture 2.0 beta 1, but will probably work with the RTW. Also please not that I’m reporting on a spike; I haven’t thoroughly tested all edge cases.

That said, the first thing we need to do is to remove AutoFixture’s default ConstructorInvoker that invokes the constructor of concrete classes. This is possible with this constructor overload:

public Fixture(DefaultRelays engineParts)

This takes as input a DefaultRelays instance, which is more or less just an IEnumerable<ISpecimenBuilder> (the basic building block of AutoFixture). We need to replace that with a filter that removes the ConstructorInvoker. Here’s a derived class that does that:

public class FilteringRelays : DefaultEngineParts
{
    private readonly Func<ISpecimenBuilder, bool> spec;
 
    public FilteringRelays(Func<ISpecimenBuilder, bool> specification)
    {
        if (specification == null)
        {
            throw new ArgumentNullException("specification");
        }
 
        this.spec = specification;
    }
 
    public override IEnumerator<ISpecimenBuilder> GetEnumerator()
    {
        var enumerator = base.GetEnumerator();
        while (enumerator.MoveNext())
        {
            if (this.spec(enumerator.Current))
            {
                yield return enumerator.Current;
            }
        }
    }
}

DefaultEngineParts already derive from DefaultRelays, so this enables us to use the overloaded constructor to remove the ConstructorInvoker by using these filtered relays:

Func<ISpecimenBuilder, bool> concreteFilter
    = sb => !(sb is ConstructorInvoker);
var relays = new FilteringRelays(concreteFilter);

The second thing we need to do is to tell the AutoMoqCustomization that it should Mock all types, not just interfaces and abstract classes. With the new (not in beta 1) overload of the constructor, we can now supply a Specification that determines which types should be mocked.:

Func<Type, bool> mockSpec = t => true;

We can now create the Fixture like this to get auto-mocking of all types:

var fixture = new Fixture(relays).Customize(
    new AutoMoqCustomization(new MockRelay(mockSpec)));

With this Fixture instance, we can now create concrete classes that are mocked. Here’s the full test that proves it:

[Fact]
public void CreateAnonymousMockOfConcreteType()
{
    // Fixture setup
    Func<ISpecimenBuilder, bool> concreteFilter
        = sb => !(sb is ConstructorInvoker);
    var relays = new FilteringRelays(concreteFilter);
 
    Func<Type, bool> mockSpec = t => true;
 
    var fixture = new Fixture(relays).Customize(
        new AutoMoqCustomization(new MockRelay(mockSpec)));
    // Exercise system
    var foo = fixture.CreateAnonymous<Foo>();
    foo.DoIt();
    // Verify outcome
    var fooTD = Mock.Get(foo);
    fooTD.Verify(f => f.DoIt());
    // Teardown
}

Foo is this concrete class:

public class Foo
{
    public virtual void DoIt()
    {
    }
}

Finally, a word of caution: this is a spike. It’s not fully tested and is bound to fail in certain cases: at least one case is when the type to be created is sealed. Since Moq can’t create a Mock of a sealed type, the above code will fail in that case. However, we can address this issue with some more sophisticated filters and Specifications. However, I will leave that up to the interested reader (or a later blog post).

All in all I think this provides an excellent glimpse of the degree of extensibility that is built into AutoFixture 2.0’s kernel.

posted on Wednesday, August 25, 2010 9:56:38 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Thursday, August 19, 2010

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

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

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

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

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

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

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

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

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

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

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

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

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

posted on Thursday, August 19, 2010 9:25:50 PM (Romance Daylight Time, UTC+02:00)  #    Comments [7] Trackback
# Monday, August 09, 2010

It gives me great pleasure to announce that AutoFixture 2.0 beta 1 is now available for download. Compared to version 1.1 AutoFixture 2.0 is implemented using a new and much more open and extensible engine that enables many interesting scenarios.

Despite the new engine and the vastly increased potential, the focus on version 2.0 has been to ensure that the current, known feature set was preserved.

What’s new?

While AutoFixture 2.0 introduces new features, this release is first and foremost an upgrade to a completely new internal architecture, so the number of new releases is limited. Never the less, the following new features are available in version 2.0:

There are still open feature requests for AutoFixture, so now that the new engine is in place I can again focus on implementing some of the features that were too difficult to address with the old engine.

Breaking changes

Version 2.0 introduces some breaking changes, although the fundamental API remains recognizable.

  • A lot of the original methods on Fixture are now extension methods on IFixture (a new interface). The methods include CreateAnonymous<T>, CreateMany<T> and many others, so you will need to include a using directive for Ploeh.AutoFixture to compile the unit test code.
  • CreateMany<T> still returns IEnumerable<T>, but the return value is much more consistently deferred. This means that in almost all cases you should instantly stabilize the sequence by converting it to a List<T>, an array or similar.
  • Several methods are now deprecated in favor of new methods with better names.

A few methods were also removed, but only those that were already deprecated in version 1.1.

Roadmap

The general availability of beta 1 of AutoFixture 2.0 marks the beginning of a trial period. If no new issues are reported within the next few weeks, a final version 2.0 will be released. If too many issues are reported, a new beta version may be necessary.

Please report any issues you find.

After the release of the final version 2.0 my plan is currently to focus on the Idioms project, although there are many other new features that might warrant my attention.

Blog posts about the new features will also follow soon.

posted on Monday, August 09, 2010 1:32:06 PM (Romance Daylight Time, UTC+02:00)  #    Comments [3] Trackback
# Tuesday, July 20, 2010

StructureMap offers several different lifetimes, among these two known as PerRequest and Unique respectively. Recently I found myself wondering what was the difference between those two, but a little help from Jeremy Miller put me on the right track.

In short, Unique is equivalent to what Castle Windsor calls Transient: every time an instance of a type is needed, a new instance is created. Even if we need the same service multiple times in the same resolved graph, multiple instances are created.

PerRequest, on the other hand, is a bit special. Each type can be viewed as a Singleton within a single call to GetInstance, but as Transient across different invocations of GetInstance. In other words, the same instance will be shared within a resolved object graph, but if we resolve the same root type once more, we will get a new shared instance – a Singleton local to that graph.

Here are some unit tests I wrote to verify this behavior (recall that PerRequest is StructureMap’s default lifestyle):

[Fact]
public void ResolveServicesWithSameUniqueDependency()
{
    var container = new Container();
    container.Configure(x =>
    {
        var unique = new UniquePerRequestLifecycle();
        x.For<IIngredient>().LifecycleIs(unique)
            .Use<Shrimp>();
        x.For<OliveOil>().LifecycleIs(unique);
        x.For<EggYolk>().LifecycleIs(unique);
        x.For<Vinegar>().LifecycleIs(unique);
        x.For<IIngredient>().LifecycleIs(unique)
            .Use<Vinaigrette>();
        x.For<IIngredient>().LifecycleIs(unique)
            .Use<Mayonnaise>();
        x.For<Course>().LifecycleIs(unique);
    });
 
    var c1 = container.GetInstance<Course>();
    var c2 = container.GetInstance<Course>();
 
    Assert.NotSame(
        c1.Ingredients.OfType<Vinaigrette>().Single().Oil,
        c1.Ingredients.OfType<Mayonnaise>().Single().Oil);
    Assert.NotSame(
        c2.Ingredients.OfType<Vinaigrette>().Single().Oil,
        c2.Ingredients.OfType<Mayonnaise>().Single().Oil);
    Assert.NotSame(
        c1.Ingredients.OfType<Vinaigrette>().Single().Oil,
        c2.Ingredients.OfType<Vinaigrette>().Single().Oil);
}
 
[Fact]
public void ResolveServicesWithSamePerRequestDependency()
{
    var container = new Container();
    container.Configure(x =>
    {
        x.For<IIngredient>().Use<Shrimp>();
        x.For<OliveOil>();
        x.For<EggYolk>();
        x.For<Vinegar>();
        x.For<IIngredient>().Use<Vinaigrette>();
        x.For<IIngredient>().Use<Mayonnaise>();
    });
 
    var c1 = container.GetInstance<Course>();
    var c2 = container.GetInstance<Course>();
 
    Assert.Same(
        c1.Ingredients.OfType<Vinaigrette>().Single().Oil,
        c1.Ingredients.OfType<Mayonnaise>().Single().Oil);
    Assert.Same(
        c2.Ingredients.OfType<Vinaigrette>().Single().Oil,
        c2.Ingredients.OfType<Mayonnaise>().Single().Oil);
    Assert.NotSame(
        c1.Ingredients.OfType<Vinaigrette>().Single().Oil,
        c2.Ingredients.OfType<Vinaigrette>().Single().Oil);
}

Notice that in both cases, the OliveOil instances are different across two independently resolved graphs (c1 and c2).

However, within each graph, the same OliveOil instance is shared in the PerRequest configuration, whereas they are different in the Unique configuration.

posted on Tuesday, July 20, 2010 10:42:53 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Monday, July 12, 2010

Occasionally I get a question about whether it is reasonable or advisable to let domain objects implement IDataErrorInfo. In summary, my answer is that it’s not so much a question about whether it’s a leaky abstraction or not, but rather whether it makes sense at all. To me, it doesn’t.

Let us first consider the essence of the concept underlying IDataErrorInfo: It provides information about the validity of an object. More specifically, it provides error information when an object is in an invalid state.

This is really the crux of the matter. Domain Objects should be designed so that they cannot be put into invalid states. They should guarantee their invariants.

Let us return to the good old DanishPhoneNumber example. Instead of accepting or representing a Danish phone number as a string or integer, we model it as a Value Object that encapsulates the appropriate domain logic.

More specifically, the class’ constructor guarantees that you can’t create an invalid instance:

private readonly int number;
 
public DanishPhoneNumber(int number)
{
    if ((number < 112) ||
        (number > 99999999))
    {
        throw new ArgumentOutOfRangeException("number");
    }
    this.number = number;
}

Notice that the Guard Clause guarantees that you can’t create an instance with an invalid number, and the readonly keyword guarantees that you can’t change the value afterwards. Immutable types make it easier to protect a type’s invariants, but it is also possible with mutable types – you just need to place proper Guards in public setters and other mutators, as well as in the constructor.

In any case, whenever a Domain Object guarantees its invariants according to the correct domain logic it makes no sense for it to implement IDataErrorInfo; if it did, the implementation would be trivial, because there would never be an error to report.

Does this mean that IDataErrorInfo is a redundant interface? Not at all, but it is important to realize that it’s an Application Boundary concern instead of a Domain concern. At Application Boundaries, data entry errors will happen, and we must be able to cope with them appropriately; we don’t want the application to crash by passing unvalidated data to DanishPhoneNumber’s constructor.

Does this mean that we should duplicate domain logic at the Application Boundary? That should not be necessary. At first, we can apply a simple refactoring to the DanishPhoneNumber constructor:

public DanishPhoneNumber(int number)
{
    if (!DanishPhoneNumber.IsValid(number))
    {
        throw new ArgumentOutOfRangeException("number");
    }
    this.number = number;
}
 
public static bool IsValid(int number)
{
    return (112 <= number)
        && (number <= 99999999);
}

We now have a public IsValid method we can use to implement an IDataErrorInfo at the Application Boundary. Next steps might be to add a TryParse method.

IDataErrorInfo implementations are often related to input forms in user interfaces. Instead of crashing the application or closing the form, we want to provide appropriate error messages to the user. We can use the Domain Object to provide validation logic, but the concern is completely different: we want the form to stay open until valid data has been entered. Not until all data is valid do we allow the creation of a Domain Object from that data.

In short, if you feel tempted to add IDataErrorInfo to a Domain Class, consider whether you aren’t about to violate the Single Responsibility Principle. In my opinion, this is the case, and you would be better off reconsidering the design.

posted on Monday, July 12, 2010 2:58:16 PM (Romance Daylight Time, UTC+02:00)  #    Comments [9] Trackback
# Tuesday, June 29, 2010

The last time I presented a sample of an AutoFixture-based unit test, I purposely glossed over the state-based verification that asserted that the resulting state of the basket variable was that the appropriate Pizza was added:

Assert.IsTrue(basket.Pizze.Any(p =>
    p.Name == pizza.Name), "Basket has added pizza.");

The main issue with this assertion is that the implied equality expression is rather weak: we consider a PizzaPresenter instance to be equal to a Pizza instance if their Name properties match.

What if they have other properties (like Size) that don’t match? If this is the case, the test would be a false negative. A match would be found in the Pizze collection, but the instances would not truly represent the same pizza.

How do we resolve this conundrum without introducing equality pollution? AutoFixture offers one option in the form of the generic Likeness<TSource, TDestination> class. This class offers convention-based test-specific equality mapping from TSource to TDestination and overriding the Equals method.

One of the ways we can use it is by a convenience extension method. This unit test is a refactoring of the test from the previous post, but now using Likeness:

[TestMethod]
public void AddWillAddToBasket_Likeness()
{
    // Fixture setup
    var fixture = new Fixture();
    fixture.Register<IPizzaMap, PizzaMap>();
 
    var basket = fixture.Freeze<Basket>();
 
    var pizza = fixture.CreateAnonymous<PizzaPresenter>();
    var expectedPizza = 
        pizza.AsSource().OfLikeness<Pizza>();
 
    var sut = fixture.CreateAnonymous<BasketPresenter>();
    // Exercise system
    sut.Add(pizza);
    // Verify outcome
    Assert.IsTrue(basket.Pizze.Any(expectedPizza.Equals));
    // Teardown
}

Notice how the Likeness instance is created with the AsSource() extension method. The pizza instance (of type PizzaPresenter) is the source of the Likeness, whereas the Pizza domain model type is the destination. The expectedPizza instance is of type Likeness<PizzaPresenter, Pizza>.

The Likeness class overrides Equals with a convention-based comparison: if two properties have the same name and type, they are equal if their values are equal. All public properties on the destination must have equal properties on the source.

This allows me to specify the Equals method as the predicate for the Any method in the assertion:

Assert.IsTrue(basket.Pizze.Any(expectedPizza.Equals));

When the Any method evalues the Pizze collection, it executes the Equals method on Likeness, resulting in a convention-based comparison of all public properties and fields on the two instances.

It’s possible to customize the comparison to override the behavior for certain properties, but I will leave that to later posts. This post only scratches the surface of what Likeness can do.

To use Likeness, you must add a reference to the Ploeh.SemanticComparison assembly. You can create a new instance using the public constructor, but to use the AsSource extension method, you will need to add a using directive:

using Ploeh.SemanticComparison.Fluent;
posted on Tuesday, June 29, 2010 8:39:30 AM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Sunday, May 23, 2010

In the next couple of weeks I will be giving a couple of talks in Copenhagen.

At Community Day 2010 I will be giving two talks on respectively Dependency Injection and TDD.

In early June I will be giving a repeat of my previous CNUG TDD talk.

posted on Sunday, May 23, 2010 6:11:37 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Tuesday, May 18, 2010

One of Castle Windsor’s facilities addresses wiring up of WCF services. So far, the sparse documentation for the WCF Facility seems to indicate that you have to configure your container in a global.asax. That’s not much to my liking. First of all, it reeks of ASP.NET, and secondly, it’s not going to work if you expose WCF over protocols other than HTTP.

However, now that we know that a custom ServiceHostFactory is effectively a Singleton, a much better alternative is to derive from the WCF Facility’s DefaultServiceHost class:

public class FooServiceHostFactory : 
    DefaultServiceHostFactory
{
    public FooServiceHostFactory()
        : base(FooServiceHostFactory.CreateKernel())
    {
    }
 
    private static IKernel CreateKernel()
    {
        var container = new WindsorContainer();
 
        container.AddFacility<WcfFacility>();
 
        container.Register(Component
            .For<FooService>()
            .LifeStyle.Transient);
        container.Register(Component
            .For<IBar>()
            .ImplementedBy<Bar>());
 
        return container.Kernel;
    }
}

Although it feels a little odd to create a container and then not really use it, but only its Kernel property, this works like a charm. It correctly wires up this FooService:

public class FooService : IFooService
{
    private readonly IBar bar;
 
    public FooService(IBar bar)
    {
        if (bar == null)
        {
            throw new ArgumentNullException("bar");
        }
 
        this.bar = bar;
    }
 
    #region IFooService Members
 
    public string Foo()
    {
        return this.bar.Baz;
    }
 
    #endregion
}

However, instead of the static CreateKernel method that creates the IKernel instance, I suggest that the WCF Facility utilizes the Factory Method pattern. As the WCF Facility has not yet been released, perhaps there’s still time for that change.

In any case, the WCF Facility saves you from writing a lot of infrastructure code if you would like to wire your WCF services with Castle Windsor.

posted on Tuesday, May 18, 2010 7:27:56 AM (Romance Daylight Time, UTC+02:00)  #    Comments [6] Trackback
# Monday, May 17, 2010

For a while I’ve been wondering about the lifetime behavior of custom ServiceHostFactory classes hosted in IIS. Does IIS create an instance per request? Or a single instance to handle all requests?

I decided to find out, so I wrote a little test service. The conclusion seems to be that there is only a single instance that servers as a factory for all requests. This is very fortunate, since it gives us an excellent place to host a DI Container. The container can then manage the lifetime of all components, including Singletons that will live for the duration of the process.

If you are curious how I arrived at this conclusion, here’s the code I wrote. I started out with this custom ServiceHostFactory:

public class PocServiceHostFactory : ServiceHostFactory
{
    private static int number = 1;
 
    public PocServiceHostFactory()
    {
        Interlocked.Increment(
            ref PocServiceHostFactory.number);
    }
 
    protected override ServiceHost CreateServiceHost(
        Type serviceType, Uri[] baseAddresses)
    {
        return new PocServiceHost(
            PocServiceHostFactory.number, serviceType,
            baseAddresses);
    }
}

The idea is that every time a new instance of ServiceHostFactory is created, the static number is incremented.

The PocServiceHostFactory just forwards the number to the PocServiceHost:

public class PocServiceHost : ServiceHost
{
    public PocServiceHost(int number, Type serviceType,
        Uri[] baseAddresses)
        : base(serviceType, baseAddresses)
    {
        foreach (var cd in 
            this.ImplementedContracts.Values)
        {
            cd.Behaviors.Add(
                new NumberServiceInstanceProvider(
                    number));
        }
    }
}

The PocServiceHost just forwards the number to the NumberServiceInstanceProvider:

public class NumberServiceInstanceProvider : 
    IInstanceProvider, IContractBehavior
{
    private readonly int number;
 
    public NumberServiceInstanceProvider(int number)
    {
        this.number = number;
    }
 
    #region IInstanceProvider Members
 
    public object GetInstance(
        InstanceContext instanceContext,
        Message message)
    {
        return this.GetInstance(instanceContext);
    }
 
    public object GetInstance(
        InstanceContext instanceContext)
    {
        return new NumberService(this.number);
    }
 
    public void ReleaseInstance(
        InstanceContext instanceContext,
        object instance)
    {
    }
 
    #endregion
 
    #region IContractBehavior Members
 
    public void AddBindingParameters(
        ContractDescription contractDescription,
        ServiceEndpoint endpoint,
        BindingParameterCollection bindingParameters)
    {
    }
 
    public void ApplyClientBehavior(
        ContractDescription contractDescription,
        ServiceEndpoint endpoint,
        ClientRuntime clientRuntime)
    {
    }
 
    public void ApplyDispatchBehavior(
        ContractDescription contractDescription,
        ServiceEndpoint endpoint,
        DispatchRuntime dispatchRuntime)
    {
        dispatchRuntime.InstanceProvider = this;
    }
 
    public void Validate(
        ContractDescription contractDescription,
        ServiceEndpoint endpoint)
    {
    }
 
    #endregion
}

The relevant part of NumberServiceInstanceProvider is the GetInstanceMethod that simply forwards the number to the NumberService:

public class NumberService : INumberService
{
    private readonly int number;
 
    public NumberService(int number)
    {
        this.number = number;
    }
 
    #region INumberService Members
 
    public int GetNumber()
    {
        return this.number;
    }
 
    #endregion
}

As you can see, NumberService simply returns the injected number.

The experiment is now to host NumberService in IIS using PocServiceHostFactory. If there is only one ServiceHostFactory per application process, we would expect that the same number (2) is returned every time we invoke the GetNumber operation. If, on the other hand, a new instance of ServiceHostFactory is created per request, we would expect the number to increase for every request.

To test this I spun up a few instances of WcfTestClient.exe and invoked the operation. It consistently returns 2 across multiple clients and multiple requests. This supports the hypothesis that there is only one ServiceHostFactory per service process.

posted on Monday, May 17, 2010 7:42:33 AM (Romance Daylight Time, UTC+02:00)  #    Comments [1] Trackback
# Tuesday, April 27, 2010

My book contains a section on the Ambient Context pattern that uses a TimeProvider as an example. It’s used like this:

this.closedAt = TimeProvider.Current.UtcNow;

Yesterday I was TDDing a state machine that consumes TimeProvider and needed to freeze and advance time at different places in the test. Always on the lookout for making unit tests more readable, I decided to have a little fun with literal extensions and TimeProvider. I ended up with this test:

// Fixture setup
var fixture = new WcfFixture();
 
DateTime.Now.Freeze();
 
fixture.Register(1.Minutes());
var sut = fixture.CreateAnonymous<CircuitBreaker>();
sut.PutInOpenState();
 
2.Minutes().Pass();
// Exercise system
sut.Guard();
// Verify outcome
Assert.IsInstanceOfType(sut.State,
    typeof(HalfOpenCircuitState));
// Teardown

There are several items of note. Imagine that we can freeze time!

DateTime.Now.Freeze();

With the TimeProvider and an extension method, we can:

internal static void Freeze(this DateTime dt)
{
    var timeProviderStub = new Mock<TimeProvider>();
    timeProviderStub.SetupGet(tp => tp.UtcNow).Returns(dt);
    TimeProvider.Current = timeProviderStub.Object;
}

This effectively sets up the TimeProvider to always return the same time.

Later in the test I state that 2 minutes pass:

2.Minutes().Pass();

I particularly like the grammatically correct English. This is accomplished with a combination of a literal extension and changing the state of TimeProvider.

First, the literal extension:

internal static TimeSpan Minutes(this int m)
{
    return TimeSpan.FromMinutes(m);
}

Given the TimeSpan returned from the Minutes method, I can now invoke the Pass extension method:

internal static void Pass(this TimeSpan ts)
{
    var previousTime = TimeProvider.Current.UtcNow;
    (previousTime + ts).Freeze();
}

Note that I just add the TimeSpan to the current time and invoke the Freeze extension method with the new value.

Last, but not least, I should point out that the PutInOpenState method isn’t some smelly test-specific method on the SUT, but rather yet another extension method.

posted on Tuesday, April 27, 2010 6:24:25 AM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback