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;

Thursday, July 30, 2009

Released Legend.Fakes on CodePlex

http://fakes.codeplex.com/

It has moved to FakeItEasy.

Read more: http://ondevelopment.blogspot.com/2009/08/changed-name-and-moved.html

Legend.Fakes configuration fluent interface

As I mentioned in my earlier post one of the things I want to avoid in my mock-/stub-/fake-framework is extension methods that clutter intellisense, this means that you have to get a configuration object to be able to start configuring your fake, don’t be afraid though, it’s really easy and there are two ways to do it. The first is to call the static method “Fake.Configure(object fakedObject)” with the fake object you want to configure, but you can also import the namespace “Legend.Fakes.ExtensionSyntax” and now you can call the “Configure” extension method directly on your faked object. If you do the latter you will have ONE extension method cluttering intellisense, but I can live with just one. Once you have the configuration object you have a fluent interface API.

IPerson person = A.Fake<IPerson>();

// Static method...
Fake.Configure(person);

// Once Legend.Fakes.ExtensionSyntax is imported you can use...
person.Configure();

 

When you have created a fake, the interface of the fake is a lot more discoverable since intellisense shows you what interface it provides: nonCluttered

The fluent interface is context aware so subsequent calls will only have certain options available depending on the call before. For example you can only specify a return value if the call you’re configuring is not a void call:

functionCall

A void call would look like this:

voidCall

Here’s some example configuration code:

var file = A.Fake<IFile>();

file.Configure()
    .CallsTo(x => x.Delete())
    .Throws(new NotSupportedException("You're not allowed to delete a file."))
    .Once();

file.Configure()
    .CallsTo(x => x.GetFileSizeInBytes()).Returns(400);

file.Name = "c:\filename.txt";

Wednesday, July 29, 2009

Introducing Legend.Fakes

OK, you’ll think I’ve lost it – or maybe you never thought I had it – but I’m creating my own mocking framework.

Why? Well, first of all because I wanted a framework that is more semantically correct and easier to understand so instead of distinguishing between mocks and stubs it just produces “fakes”, if a fake is a mock or a stub depends on the use of it. I also wanted a simpler and cleaner syntax for configuration, I’m really not a fan of the many extension methods cluttering Intellisense in your tests when using Rhino Mocks (although I really love Rhino Mocks).

clutternedIntellisense

I also thought it would be a really nice learning experience. Finally there are a few features I think will be cool that I will include that no other framework has (to my knowledge, though I’m only really familiar with Rhino).

But the main feature is and should be ease of use, so, to create a fake object (whether it’s a mock or a stub) you’d write this:

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

I’ll write more about other features, my learning experience while implementing this and post code soon.