Saturday, October 24, 2009

Asserting on exception messages in NUnit

It seems to me that a lot of developers has missed the fact that Assert.Throws<T> in NUnit actually returns the thrown exception which lets you assert on the message (and other properties of the exception). I wrote a response to a question on Stack Overflow which talks about this:

http://stackoverflow.com/questions/1609536/nunit-assert-throws

Saturday, September 5, 2009

Fake scopes explained

FakeItEasy has a scoping feature that lets you configure calls only within a scope or asserting that calls was made within a specific scope.

A scope implements IDisposable and the Dispose method closes the scope, this means that to create a scope you create a using statement for it:

using (Fake.CreateScope())
{
    // Do something within the scope...
}

Any calls configured within a scope are only valid within that scope, this means that you can override the behavior of a faked method for just a small part of your test, for example:

public void Configuring_calls_in_scope()
{
    var factory = A.Fake<IWidgetFactory>();

    factory.Configure().CallsTo(x => x.Create()).Returns(A.Fake<IWidget>());

    using (Fake.CreateScope())
    {
        factory.Configure().CallsTo(x => x.Create()).Throws(new Exception());

        // This will throw since the method was configured in this scope.
        factory.Create();
    }

    // This will return a fake widget as configured before entering the scope.
    var widget = factory.Create();
}

Scopes also affects what calls are visible when getting the calls made to a fake object, when you’re inside a child scope and use the Fake.GetCalls(foo)-method or the RecordedCalls-property on a Fake<T>-object only the calls made within that scope are visible. In an outer scope the calls made in the outer scope and any child scope are visible:

public void Getting_calls_in_scope()
{
    var factory = A.Fake<IWidgetFactory>();

    factory.Configure().CallsTo(x => x.Create()).Returns(A.Fake<IWidget>());

    var widget = factory.Create();

    // This will succeed since there was a call to the create method
    // in the current scope.
    Fake.Assert(factory).WasCalled(x => x.Create());

    using (Fake.CreateScope())
    {
        // This will produce 0, no calls were made to the create method 
        // in the current scope.
        int numberOfCalls = Fake.GetCalls(factory).Matching(x => x.Create());

        // This will throw:
        Fake.Assert(factory).WasCalled(x => x.Create());
    }

    using (Fake.CreateScope())
    {
        factory.Create();
    }

    // This will now return 2 since there was one call in the outer scope
    // and another one in the inner scope.
    int numberOfCalls = Fake.GetCalls(factory).Matching(x => x.Create());
}

The other way of faking it

I’ve added a new way to create fake objects in FakeItEasy. You might call the “traditional” way of doing it in FakeItEasy is the “Rhino-style”:

public static void TraditionalWay()
{
    var foo = A.Fake<IFoo>();
    foo.Configure().CallsTo(x => x.Baz()).Returns(10);

    int value = foo.Baz();

    Fake.Assert(foo).WasCalled(x => x.Baz());
}

When creating fakes in this way the returned faked object is of the type specified in the A.Fake-call, faking an IFoo returns an IFoo. When creating a fake the new way, which we might call the “Moq-style” you instead create a fake object that provides an api for configuring the faked object as well as a reference to the faked object:

public static void TheOtherWay()
{
    var foo = new Fake<IFoo>();
    foo.CallsTo(x => x.Baz()).Returns(10);

    int value = foo.FakedObject.Baz();

    foo.Assert().WasCalled(x => x.Baz());
}

Both styles are equally supported so that the developer can choose what ever style he/she is most comfortable with.

Saturday, August 22, 2009

Upcasting vs. downcasting

I always seem to forget which is which so I guess I’ll write it down here once and for all.

image

Casting from a Circle or Rectangle to a Shape is upcasting, casting up in the hierarchy.

Casting from a Shape object to a Circle object is downcasting, casting down in the hierarchy. If you find yourself downcasting, it may be an indication of a code smell, think twice about it!

Changed name and moved

No, I didn’t join the witness protection program or anything like that, it’s not my name that changed, and I didn’t move. However I did change the name of the mock-/stub-/fake-framework Legend.Fakes to the – in my opinion – catchier FakeItEasy and I also moved the source to from CodePlex to Google code since the svn support is way better there.

The new location of the source is: http://code.google.com/p/fakeiteasy/

Friday, August 7, 2009

Fake wrappers (candy inside)

I added a new feature to FakeItEasy the other day, it lets you put a fake wrapper around a real instance. This means that all calls that are not explicitly configured to do anything different are delegated to the wrapped instance, this gives you the ability to fake out only a certain method on a fake.

For example, you might have a web service of some sort:

public interface IStoreService
{
    IEnumerable<IProduct> FindAllProducts();
    int BuyProduct(IProduct product);
}

public interface IProduct
{
    string ProductId { get; }
    decimal Price { get; }
}

Let’s say in an integration test of a class we are writing called PersonalShopper you want to run against an actual (let’s event say a sealed) implementation of this service, we can call it RidiculouslyOverPricedStore, but you want to fake out the BuyProduct-method so that nothing is actually booked in the remote system.

Here’s the PersonalShopper class we want to write an integration test for:

public class PersonalShopper
{
    private IStoreService store;

    public PersonalShopper(IStoreService store)
    {
        this.store = store;
    }

    public IProduct BuyMeSomething()
    {
        var productToBy =
            (from product in this.store.FindAllProducts()
             orderby product.Price
             select product).First();

        this.store.BuyProduct(productToBy);
    }
}

Here’s a test for this where we create a fake wrapping an instance of the RidiculouslyOverPricedStore-class, we then configure calls to the BuyProduct-method with any product to return 1 (this is meant to be the order id).

[Test]
public void Personal_shopper_buys_a_product()
{
    // Arrange
    var realStore = new RidiculouslyOverPricedStore();
    var fakedStore = A.Fake<IStoreService>(x => x.Wrapping(realStore));

    A.CallTo(() => fakedStore.BuyProduct(A<IProduct>.Ignored.Argument)).Returns(1);

    var shopper = new PersonalShopper(fakedStore);

    // Act
    var boughtProduct = shopper.BuyMeSomething();

    // Assert
    Assert.That(boughtProduct, Is.Not.Null);
}

Another case to use this feature is if you have a class that you want to use in your test that you don’t have to configure at all, but you still want to assert that a certain method was called, just wrap an instance, use it as normal without configuring it and use Fake.Assert to assert on it.

Friday, July 31, 2009

Event raising syntax

Syntax for event raising is kind of awkward across the line, and for good reason, there simply is no really good way of doing it since an event always has to be positioned to the of an event attachment or detachment (+= or –=).

Just from the top of my head I think the way it’s done (or rather one of the ways you can do it) in Rhino Mocks is something like this:

var foo = MockRepository.GenerateMock<IFoo>();
foo.Raise(x => x.SomethingHappened += null, foo, EventArgs.Empty);

I think (I have not implemented this yet so I’m not sure it works) that I just came up with a rather different and maybe simpler way of doing it for Legend.Fakes. If it’s simpler or not I’ll leave up to you, but there’s a definite benefit in that it’s type safe on the event argument:

var foo = A.Fake<IFoo>();

// with sender explicitly:
foo.SomethingHappened += Raise.With(foo, EventArgs.Empty).Now;

// with the fake object as sender:
foo.SomethingHappened += Raise.With(EventArgs.Empty).Now;