# Monday, October 26, 2009

A few months ago I described how you can use AutoFixture's With method to assign property values as part of building up an anonymous variable. In that scenario, the With method is used to explicitly assign a particular, pre-defined value to a property.

There's another overload of the With method that doesn't take an explicit value, but rather uses AutoFixture to create an anonymous value for the property. So what's the deal with that if AutoFixture's default behavior is to assign anonymous values to all writable properties?

In short it's an opt-in mechanism that only makes sense if you decide to opt out of the AutoProperties features.

As always, let's look at an example. This time, I've decided to show you a slightly more realistic example so that you can get an idea of how AutoFixture can be used to aid in unit testing. This also means that the example is going to be a little more complex than usual, but it's still simple.

Imagine that we wish to test that an ASP.NET MVC Controller Action returns the correct result. More specifically, we wish to test that the Profile method on MyController returns a ViewResult with the correct Model (the current user's name, to make things interesing).

Here's the entire test. It may look more complicated than it is – it's really only 10 lines of code, but I had to break them up to prevent unpleasant wrapping if your screen is narrow.

[TestMethod]
public void ProfileWillReturnResultWithCorrectUserName()
{
    // Fixture setup
    var fixture = new Fixture();
    fixture.Customize<ControllerContext>(ob => ob
        .OmitAutoProperties()
        .With(cc => cc.HttpContext));
 
    var expectedUserName = 
        fixture.CreateAnonymous("UserName");
 
    var httpCtxStub = new Mock<HttpContextBase>();
    httpCtxStub.SetupGet(x => x.User).Returns(
        new GenericPrincipal(
            new GenericIdentity(expectedUserName), null));
    fixture.Register(httpCtxStub.Object);
 
    var sut = fixture.Build<MyController>()
        .OmitAutoProperties()
        .With(c => c.ControllerContext)
        .CreateAnonymous();
    // Exercise system
    ViewResult result = sut.Profile();
    // Verify outcome
    var actual = result.ViewData.Model;
    Assert.AreEqual(expectedUserName, actual, "User");
    // Teardown
}

Apart from AutoFixture, I'm also making use of Moq to stub out HttpContextBase.

You can see the Anonymous With method in two different places: in the call to Customize and when the SUT is being built. In both cases you can see that the call to With follows a call to OmitAutoProperties. In other words: we are telling AutoFixture that we don't want any of the writable properties to be assigned a value except the one we identify.

Let me highlight some parts of the test.

fixture.Customize<ControllerContext>(ob => ob
    .OmitAutoProperties()
    .With(cc => cc.HttpContext));

This line of code instructs AutoFixture to always create a ControllerContext in a particular way: I don't want to use AutoProperties here, because ControllerContext has a lot of writable properties of abstract types, and that would require me to set up a lot of Test Doubles if I had to assign values to all of those. It's much easier to simply opt out of this mechanism. However, I would like to have the HttpContext property assigned, but I don't care about the value in this statement, so the With method simply states that AutoFixture should assign a value according to whatever rule it has for creating instances of HttpContextBase.

I can now set up a Stub that populates the User property of HttpContextBase:

var httpCtxStub = new Mock<HttpContextBase>();
httpCtxStub.SetupGet(x => x.User).Returns(
    new GenericPrincipal(
        new GenericIdentity(expectedUserName), null));
fixture.Register(httpCtxStub.Object);

This is registered with the fixture instance which closes the loop to the previous customization.

I can now create an instance of my SUT. Once more, I don't want to have to set up a lot of irrelevant properties on MyController, so I opt out of AutoProperties and then explicitly opt in on the ControllerContext. This will cause AutoFixture to automatically populate the ControllerContext with the HttpContext Stub:

var sut = fixture.Build<MyController>()
    .OmitAutoProperties()
    .With(c => c.ControllerContext)
    .CreateAnonymous();

For completeness' sake, here's the MyController class that I am testing:

public class MyController : Controller
{
    public ViewResult Profile()
    {
        object userName = this.User.Identity.Name;
        return this.View(userName);
    }
}

This test may seem complex, but it really accomplishes a lot in only 10 lines of code, considering that ASP.NET MVC Controllers with a working HttpContext are not particularly trivial to set up.

In summary, this With method overload lets you opt in on one or more explicitly identified properties when you have otherwise decided to omit AutoProperties. As all the other Builder methods, this method can also be chained.

posted on Monday, October 26, 2009 9:26:49 PM (Romance Standard Time, UTC+01:00)  #    Comments [0] Trackback
# Saturday, October 24, 2009

Daniel Frost has published a podcast where he discusses WCF with me. It's about half an hour and in Danish. Hear it here.

posted on Saturday, October 24, 2009 3:52:18 AM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Monday, October 05, 2009

For the last few months I've been writing a book for Manning tentatively titled Dependency Injection in .NET. The page about the book is now live at the Manning web site where you can read more about it and, if you would like, purchase an Early Access edition and read the chapters as they are being written.

If you have ever wanted to learn about Dependency Injection (DI) related to .NET, here's your chance!

At the moment I'm about a third of the way into the book, so there's still some way to go, but I hope to be done with it in 2010.

If you decide to purchase an Early Access edition, I'd love to receive your feedback in the online forum.

posted on Monday, October 05, 2009 8:13:50 PM (Romance Daylight Time, UTC+02:00)  #    Comments [4] Trackback
# Tuesday, September 29, 2009

The SOLID principles of OOD as originally put forth by Robert C. Martin make for such a catchy acronym, although they seem to originally have been spelled SOLDI.

In any case I've lately been thinking a bit about these principles and it seems to me that the Single Responsibility Principle (SRP) and the Interface Segregation Principle (ISP) seem to be very much related. In essence you could say that the ISP is simply SRP applied to interfaces.

The notion underlying both is that a type should deal with only a single concept. Whether that applies to the public API or the internal implementation is less relevant because a corollary to the Liskov Substitution Principle (LSP) and Dependency Inversion Principle (DIP) is that we shouldn't really care about the internals (unless we are actually implementing, that is).

The API is what matters.

Although I do understand the subtle differences between SRP and ISP I think they are so closely related that one of them is really redundant. We can remove the ISP and still have a fairly good acronym: SOLD (although SOLID is still better).

There's one principle that I think is missing from this set: The principle about Command/Query Separation (CQS). In my opinion, this is a very important principle that should be highlighted more than is currently the case.

If we add CQS to SOLD, we are left with some less attractive acronyms:

  • SCOLD
  • COLDS
  • CLODS

Not nearly as confidence-inspiring acronyms as SOLID, but nonetheless, I'm striving to write COLDS code.

posted on Tuesday, September 29, 2009 9:38:42 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Tuesday, September 22, 2009

In the previous post on AutoFixture, I demonstrated how it's possible to use a customized Builder to perform complex initialization when requesting an instance of a particular type. To recap, this was the solution I described:

var mc = fixture.CreateAnonymous<MyClass>();
var mvm = fixture.Build<MyViewModel>()
    .Do(x => x.AvailableItems.Add(mc))
    .With(x => x.SelectedItem, mc)
    .CreateAnonymous();

This code first creates an anonymous instance of MyClass that can be added to MyViewModel. It then initializes a Builder for a specific instance of MyViewModel, instructing it to

  1. add the anonymous MyClass instance to the list of AvailableItems
  2. assign the same instance to the SelectedItem property

While this works splendidly, it can get tiresome to write the same customization over and over again if you need to create multiple instances of the same type. It also violate the DRY principle.

When this is the case, you can alternatively register a customized Builder pipeline for the type in question (in this case MyViewModel). This is done with the Customize method:

var mc = fixture.CreateAnonymous<MyClass>();
fixture.Customize<MyViewModel>(ob => ob
    .Do(x => x.AvailableItems.Add(mc))
    .With(x => x.SelectedItem, mc));

The Customize method takes as input a function that provides an initial ObjectBuilder as input, and returns a new, customized ObjectBuilder as output. This function is registered with the type, so that each time an anonymous instance of the type is requested, the customized ObjectBuilder will be used to create the instance.

In the example, I customize the supplied ObjectBuilder (ob) in exactly the same way as before, but instead of invoking CreateAnonymous, I simply return the customized ObjectBuilder to the Fixture instance. It then saves this customized ObjectBuilder for later use.

With this customization, what before failed now succeeds:

var mvm = fixture.CreateAnonymous<MyViewModel>();

The Customize method is the core method for customizing AutoFixture. Most other customization methods (like Register) are simply convenience methods that wraps Customize. It is a very powerful method that can be used to define some very specific Builder algorithms for particular types.

posted on Tuesday, September 22, 2009 4:53:48 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Monday, September 21, 2009

Yesterday I released version .8.6 of AutoFixture. It is a minor release that simply adds some new features.

There are some minor breaking changes (documented on the release page), but they only affect supporting classes and don't touch on any of the code examples I have so far published. In other words, if you are using AutoFixture's fluent interface, your code should still compile.

Please go ahead and download it and use it. As always, comments and questions are welcome, either here or in the forum.

posted on Monday, September 21, 2009 7:37:36 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Monday, September 07, 2009

How can you make an AJAX link that updates itself in ASP.NET MVC? My colleague Mikkel and I recently had that problem and we couldn't find any guidance on this topic, so now that we have a solution, I thought I'd share it.

The problem is simple: We needed a link that invoked some server side code and updated the text of the link itself based on the result of the operation. Here is a simplified example:

image

Each time you click the link, it should invoke a Controller Action and return a new number that should appear as the link text.

This is pretty simple to implement once you know how. The first thing to realize is that the link and all the AJAX stuff must be placed in a user control. The only thing that needs to go into the containing page is the containing element itself:

<h2>Self-updating AJAX link</h2>
Click the link to update the number:
<span id="thespan">
    <% this.Html.RenderPartial("NumberAjaxUserControl"); %>
</span>

Notice the id of the span element – this same id will be referenced from the user control.

To bootstrap this view, the Controller Action for the page contains code that assigns an initial value to the number (in this case 1):

public ActionResult Index()
{
    this.ViewData["number"] = 1.ToString();
    return this.View();
}

To keep the example simple, I simply add the number to the ViewData dictionary, but in any production implementation, I would opt to use a strongly typed ViewModel instead.

The NumberAjaxUserControl itself only contains the definition of the AJAX link:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl" %>
<%@ Import Namespace="System.Web.Mvc.Ajax" %>
<%= this.Ajax.ActionLink((string)this.ViewData["number"],
    "GetNext",
    new { number = this.ViewData["number"] }, 
    new AjaxOptions { UpdateTargetId = "thespan" })%>

The first parameter to the ActionLink method is simply the current number to render as the link text. Since I'm using the untyped ViewData dictionary for this example, I need to cast it to a string.

The next parameter ("GetNext") indicates the Controller Action to invoke when the link is clicked – I will cover that shortly.

The third parameter is a Route Value that specifies that the parameter number with the correct value will be supplied to the GetNext Controller Action. It uses the number stored in ViewData.

The last parameter indicates the id of the element to update. Recall from before that this name was "thespan".

The only missing piece now is the GetNext Controller Action:

public PartialViewResult GetNext(int number)
{
    this.ViewData["number"] = (number + 1).ToString();
    return this.PartialView("NumberAjaxUserControl");
}

In this example I simply chose to increment the number by one, but I'm sure you can imagine that this method could just as well perform a database lookup or something similar.

Notice that the method returns a PartialViewResult that uses the same user control that I used to bootstrap the thespan element. This means that every time the link is clicked, the GetNext method is updated, and the exact same user control is used to render the content that dynamically replaces the original content of the element.

posted on Monday, September 07, 2009 8:14:39 PM (Romance Daylight Time, UTC+02:00)  #    Comments [2] Trackback
# Wednesday, September 02, 2009

It gives me great pleasure to announce that I have just release version .8.5 of AutoFixture. It is a minor release (hence the numbering) that mainly contains a lot of convenience overloads to already existing methods. There is also a single bug fix.

There are two breaking changes (documented on the release page), but they are minor and I do not expect them to cause problems. Only one of these even remotely affects any part of the API I have already discussed here, and that relates to what kind of exception is being thrown when AutoFixture is unable to create an instance of the requested type.

Please go ahead and download it and use it heavily :) As always, comments and questions are welcome.

posted on Wednesday, September 02, 2009 10:21:13 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback
# Tuesday, August 25, 2009

Soon after I posted my post on the AutoFixture Custom Builder's Do method, a much better example occurred to me, so let's revisit this feature in light of a more reasonable context.

When I write WPF code, I always use the MVVM pattern. When I need to create a Master/Detail View, I usually model it so that my View Model has a list of available items, and a property that returns the currently selected item. In this way, I can bind the current Detail View to the currently selected item purely through the View Model.

Such a View Model might look like this:

public class MyViewModel
{
    private readonly List<MyClass> availableItems;
    private MyClass selectedItem;
 
    public MyViewModel()
    {
        this.availableItems = new List<MyClass>();
    }
 
    public ICollection<MyClass> AvailableItems
    {
        get { return this.availableItems; }
    }
 
    public MyClass SelectedItem
    {
        get { return this.selectedItem; }
        set 
        {
            if (!this.availableItems.Contains(value))
            {
                throw new ArgumentException("...");
            }
            this.selectedItem = value;
        }
    }
}

The main point of interest is that if you attempt to set SelectedItem to an instance that's not contained in the list of available items, an exception will be thrown. That's reasonable behavior, since we want the user to select only from the available items.

By default, AutoFixture works by assigning an Anonymous Value to all writable properties. Since these values are auto-generated, the value AutoFixture is going to assign to SelectedItem will be a new instance of MyClass, and thus not one of the available items. In other words, this will throw an exception:

var mvm = fixture.CreateAnonymous<MyViewModel>();

There are several solutions to this situation, depending on the scenario. If you need an instance with SelectedItem correctly set to a non-null value, you can use the Do method like this:

var mc = fixture.CreateAnonymous<MyClass>();
var mvm = fixture.Build<MyViewModel>()
    .Do(x => x.AvailableItems.Add(mc))
    .With(x => x.SelectedItem, mc)
    .CreateAnonymous();

This first creates an anonymous instance of MyClass, adds it to AvailableItems as part of a customized Builder pipeline and subsequently assigns it to SelectedItem.

Another option is to skip assigning only the SelectedItem property. This is a good option if you don't need that value in a particular test. You can use the Without method to do that:

var mvm = fixture.Build<MyViewModel>()
    .Without(s => s.SelectedItem)
    .CreateAnonymous();

This will assign a value to all other writable properties of MyViewModel (if it had had any), except the SelectedItem property. In this case, the value of SelectedItem will be null, since it is being ignored.

Finally you can simply choose to omit all AutoProperties using the OmitAutoProperties method:

var mvm = fixture.Build<MyViewModel>()
    .OmitAutoProperties()
    .CreateAnonymous();

In this scenario, only MyViewModel's constructor is being executed, while all writable properties are being ignored.

As you can see, AutoFixture offers great flexibility in providing specialized custom Builders that fit almost any situation.

posted on Tuesday, August 25, 2009 8:27:39 PM (Romance Daylight Time, UTC+02:00)  #    Comments [2] Trackback
# Monday, August 17, 2009

The default behavior of AutoFixture is to create an Anonymous Variable by assigning a value to all writable properties of the created instance. This is great in many scenarios, but not so much in others. You can disable this behavior by using the OmitAutoProperties method, but sometimes, you would like most of the writable properties set, except one or two.

Consider this simple Person class:

public class Person
{
    private Person spouse;
 
    public DateTime BirthDay { get; set; }
 
    public string Name { get; set; }
 
    public Person Spouse 
    {
        get { return this.spouse; }
        set
        {
            this.spouse = value;
            if (value != null)
            {
                value.spouse = this;
            }
        }
    }
}

The main trouble with this class, seen from AutoFixture's perspective, is the circular reference exposed by the Spouse property. When AutoFixture attempts to create an anonymous instance of Person, it will create anonymous values for all writable properties, and that includes the Spouse property, so it attempts to create a new instance of the Person class and assign values to all public properties, including the Spouse property, etc.

In other words, this line of code throws a StackOverflowException:

var person = fixture.CreateAnonymous<Person>();

If you would still like to have anonymous values assigned to Name and BirthDay, you can use the Without method:

var person = fixture.Build<Person>()
    .Without(p => p.Spouse)
    .CreateAnonymous();

This will give you an anonymous instance of the Person class, but with the Spouse property still with its default value of null.

Several calls to Without can be chained if you want to skip more than one property.

posted on Monday, August 17, 2009 9:33:40 PM (Romance Daylight Time, UTC+02:00)  #    Comments [0] Trackback