# Tuesday, April 28, 2009

At May 12 2009 I'll be speaking at 7N's IT Konference 2009 (in Danish, so that's no spelling error). You can read the program here.

The topic of my talk will be TDD patterns and terminology, so I'll discuss Fixtures, Stubs, Mocks and the like. As always, xUnit Test Patterns will form the basis of my vocabulary.

Of the other speakers, I'm particularly looking forward to hear my good friend Martin Gildenpfennig from Ative speak!

posted on Tuesday, April 28, 2009 11:02:32 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Monday, April 27, 2009

Several times in my previous AutoFixture posts, I’ve insinuated that you can change the algorithms used for creating strings, numbers and so on, if you don’t like the defaults.

One way you can do this is by simply using the Register method that I introduced in my previous post. Let’s say that you want to replace the string algorithm to simply return a specific string:

fixture.Register<string>(() => "ploeh");

No matter how many times you’ll call CreateAnonymous<string> on that particular fixture object, it will always return ploeh.

The Register method is really only a type-safe convenience method that wraps access to the TypeMappings property. TypeMappings is just a Dictionary of types mapped to functions. By default, the Fixture class has a set of pre-defined TypeMappings for primitive types such as strings, numbers and booleans, so you could access the function used to generate strings by indexing into this Dictionary with the System.String type.

Equivalent to the above example, you could alternatively replace the string algorithm like this:

fixture.TypeMappings[typeof(string)] = s => "fnaah";

Instead of using the Register method, I here assign a lambda expression directly to the key identified by the System.String type. This is what the Register method does, so the result is exactly the same.

However, you may have noticed that by accessing TypeMappings directly, the signature of the function is different. The Register method takes a Func<T>, whereas the TypeMappings Dictionary expects a Func<object, object>. As you can see, the Register method is more type-safe, but the TypeMappings Dictionary gives you a chance to utilize the optional seed that one of the CreateAnonymous overloads takes.

You could, for example, do this:

fixture.TypeMappings[typeof(string)] = s =>
    string.Format((string)s, new Random().Next(100));

Although this particular algorithm has a built-in weakness (can you spot it?), we can now use the seed to provide a format string, like this:

string result = fixture.CreateAnonymous("Risk: {0}%");

which will yield a result like Risk: 32%.

When I designed the extensibility mechanism for AutoFixture, I seriously considered defining an interface that all TypeMappings had to implement, but I ended up preferring a Func<object, object> instead, since this allows you to redefine a particular algorithm inline in a test by using an anonymous delegate or lambda expression, and you can also reuse an existing algorithm, as long as it fits the signature.

posted on Monday, April 27, 2009 7:42:07 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Thursday, April 23, 2009

Now that I’ve described how AutoFixture creates objects, it’s time to look at a bit more advanced scenario. As you may recall, AutoFixture creates an object graph based on the public constructors of the types contained in that object graph.

That’s all well and good when all involved types have public constructors, but what happens when this is not the case?

Imagine that the MyClass constructor has this signature:

public MyClass(IMyInterface mi)

Since IMyInterface is an interface it has no public constructors, so this will not work:

Fixture fixture = new Fixture();
MyClass sut = fixture.CreateAnonymous<MyClass>();

The second line of code will throw an ArgumentException ObjectCreationException* stating that “AutoFixture was unable to create an instance of type Ploeh.QualityTools.AutoFixtureDocumentationTest.Intermediate.IMyInterface, since it has no public constructor.” Not terribly surprising, actually.

To resolve this issue, the Register method allows you to specify a custom function that creates an object of the requested type. In the case of IMyInterface, that would be a Func<IMyInterface>:

Fixture fixture = new Fixture();
fixture.Register<IMyInterface>(() => 
    new FakeMyInterface());
MyClass sut = fixture.CreateAnonymous<MyClass>();

Here, I use a lambda expression to register the FakeMyInterface type, so that every time that particular Fixture instance is asked to create an instance of IMyInterface, it will invoke the lambda expression, and thus return an instance of FakeMyInterface (which obviously implements IMyInterface).

The Register method simply lets you map types without public constructors to concrete types created by a function you specify.

A more advanced scenario arises if you wish to use a specific text with this FakeMyInterface constructor overload:

public FakeMyInterface(int number, string text)

Obviously, you can do it manually like this:

Fixture fixture = new Fixture();
int anonymousNumber = fixture.CreateAnonymous<int>();
string knownText = "This text is not anonymous";
fixture.Register<IMyInterface>(() => 
    new FakeMyInterface(anonymousNumber, knownText));

Here, I simply use the fixture object to create an anonymous number, while the knownText variable is explicitly assigned a value, and then both are used as outer variables in the Register function.

This is, however, a common scenario, so the Register method has some convenience overloads that will supply anonymous input parameters for you to use or throw away as you like. This means that I can rewrite the above example to this:

Fixture fixture = new Fixture();
string knownText = "This text is not anonymous";
fixture.Register<int, string, IMyInterface>((i, s) => 
    new FakeMyInterface(i, knownText));

Compared to the previous example, I save a line of code. The drawback is that I have to explicitly specify the type parameters to the Register method. In my book, that’s a pretty good tradeoff, as it removes a line of irrelevant code, and allows the test to focus on the relevant parts.

Notice that this Register overload creates both an anonymous integer and an anonymous string, but since I don’t want to use the anonymous string (s), I just ignore it and use the knownText variable instead.

*Edit (2009-09-02): Changed the name of the Exception type to correctly reflect a breaking change introduced in AutoFixture .8.5.

posted on Thursday, April 23, 2009 9:51:42 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Sunday, April 19, 2009

(Just back after 14 days in Morocco, I'll pick up where I left…)

The last group of built-in special creation algorithms for AutoFixture, besides strings and numbers, concerns Booleans.

The default algorithm is to alternate between true and false, starting with true; i.e. the first time you invoke

fixture.CreateAnonymous<bool>();

it will return true, the next time false, then true again, etc.

The reason I chose this algorithm was because I wanted to ensure that the first time AutoFixture creates an anonymous Boolean, it will return true, which is different than the default (false, in case you were in doubt). This gives us better assurance that a given constructor argument or property is being assigned a real value instead of the default.

Like with numbers, using the overload that takes a seed has no effect, and the seed is simply ignored.

fixture.CreateAnonymous(true);

In other words, the above method is still going to return false every second time, so it doesn’t really make sense to use this overload at all for Booleans (or numbers).

posted on Sunday, April 19, 2009 7:40:36 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Friday, April 03, 2009

Previously, we saw how AutoFixture creates strings. In this post, I’ll explain how it creates numbers. Once again, the algorithm that I’ll explain here is the default algorithm, but if you don’t like it, you can replace it with something else.

It’s very simple: Numbers are returned in the ordered sequence of natural numbers (1, 2, 3, 4, 5, …). The first time you call

fixture.CreateAnonymous<int>();

the returned number will be 1, the second time 2, etc.

The reason I chose that particular algorithm is because it creates numbers that we, as humans, find… well… natural!

A lot of the domains we model work with natural numbers, and even if you write an API where negative numbers are allowed, it’s fairly unlikely that positive numbers will not be allowed. Thus, in most cases, small positive integers tend to be ‘nice’ values in most APIs – and recall that when we do TDD, we focus on the Happy Path, so it’s important to pick values that take us down that path.

Using the overload that takes a seed, like this:

fixture.CreateAnonymous(42);

has no effect – the seed (in this case 42) is simply ignored, so if you call this after first calling the parameterless overload twice, the return number is going to be 3.

Each number type, however, has its own sequence, so even if you’ve been creating a few Int32 instances like above,

fixture.CreateAnonymous<decimal>();

will return 1.

The following number types all work that way:

  • Byte
  • Decimal
  • Double
  • Int16
  • Int32
  • Int64
  • SByte
  • Single
  • UInt16
  • UInt32
  • UInt64
posted on Friday, April 03, 2009 11:07:13 PM (Romance Daylight Time, UTC+02:00)  #    Comments [4] Trackback
# Thursday, April 02, 2009

As previously hinted, AutoFixture creates primitive types like strings, numbers, etc. using special algorithms.

In this post, I’ll describe the default algorithm for strings. If you don’t like this particular algorithm, you can replace it with your own.

If you don’t care about the created string at all, you can just create it like this:

string anonymousText = 
    fixture.CreateAnonymous<string>();

The algorithm is simply to create a new Guid and convert it to a string, so that anonymousText will have a value like “f5cdf6b1-a473-410f-95f3-f427f7abb0c7”. Obviously, you don’t know exactly which value will be returned, but that’s the whole point of Constrained Non-Determinism.

When I create string values as Explicit Expectations, I prefer that the Assert failure message contains some sort of hint for me, so I can instead provide a hint to the CreateAnonymous method:

string anonymousName = fixture.CreateAnonymous("Name");

This overload is still generic, but since I provide a string as input, type inferencing takes care of the rest.

This is still going to create a Guid, but will now prepend the hint, giving a string like “Name30a35da1-d681-441b-9db3-77ff51728b58”.

Now, when my test fails, I’ll get an error message equivalent to

“Assert.AreEqual failed. Expected:<Namef2b1f55b-e9dc-4aac-a1ab-128dc80d3b71>. Actual:<ploeh>. Boo hiss”

which I find marginally more informative than if the hint hadn’t been there.

In a future post, I’ll explain how you can replace this algorithm with something else.

posted on Thursday, April 02, 2009 7:29:35 AM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback