Sunday, December 21, 2008

Test Data Builder

In every project you reach a point where you need test data for unit testing. Having a reasonably complex domain model can make this task "difficult" because testing an entity in many cases means that you also have to setup associations to other entities. Intializing objects per test is cumbersome and any changes to constructor arguments will break your tests. One of the solutions to this problem is to use the Object Mother pattern. It's basically a class with factory methods that helps you setup an object for testing. The object creation code is moved out of the tests so that it can be reused and making the test data more maintainable. So if you are developing a scrum application and want to create a project with a sprint and a user story you would do something like this:

public static class ProjectMother
{
 public static Project CreateProjectWithSprint()
 {
     Project project = new Project();
     Sprint sprint = new Sprint();
     UserStory userStory = new UserStory();
     userStory.Name = "User story";
     userStory.StoryPoints = 8;
     sprint.AddUserStory(userStory);
     project.AddSprint(sprint);
     return project;
 }
}

Project project = ProjectMother.CreateProjectWithSprintAndUserStories();
However as time goes by you end up with a lot of factory methods for the slightest variation in the test data beacuse of the heavy coupling that exists since many tests use the same method. This make the Object Mother class hard to maintain. To solve this problem I usually write a fluent interface (embedded domain specific language) that I use to initalize my objects for testing. This is heavily based on the Expression Builder pattern. For each class I want to test I write a builder for that class. So when I want to create a Project object I just write:
Project project = ProjectBuilder.Create.Project
              .WithName("Test Project")
              .WithSprint(SprintBuilder.Create.Sprint
                  .WithName("Sprint 1")
                  .WithUserStory(UserStoryBuilder.Create.UserStory
                      .WithName("Story 1")
                      .WithStoryPoints(13)
                      .WithTask(TaskBuilder.Create.Task
                          .WithName("Task 1")
                          .WithHours(3))));

Behind the scenes the ProjectBuilder takes care of everything adding sprints and so on. In each method the builder just returns itself after having done some setup on the private Project instance. The ProjectBuilder is finally casted to Project using an implicit cast operator which returns the private Project instance.
public class ProjectBuilder
{
 private static Project mProject;

 public static ProjectBuilder Create
 {
     get { return new ProjectBuilder(); }
 }

 public ProjectBuilder WithName(string name)
 {
     mProject.Name = name;
     return this;
 }

 public ProjectBuilder Project
 {
     get
     {
         mProject = new Project { Name = "Test Project" };
         return this;
     }
 }

 public ProjectBuilder WithSprint(Sprint sprint)
 {
     mProject.AddSprint(sprint);
     return this;
 }

 public ProjectBuilder WithBacklog(Backlog backlog)
 {
     mProject.Backlog = backlog;
     return this;
 }

 public static implicit operator Project(ProjectBuilder builder)
 {
     return mProject;
 }

}
Still, I don't feel that the Object Mother and the Builder are mutually exclusive. If I have a lot of tests that use the same test data I often create an Object Mother with a factory method that uses the builders. When I need a specialized initialization of an object for a test I just use the builders directly in my tests.

I find this way of creating test data really useful and hopefully you do too! Feel free to download and use the code. The builders are located in the tests project.

Merry Christmas!!

Thursday, November 20, 2008

Presentation at NNUG Vestfold

Last night I held a presentation at NNUG Vestfold. I primarily held demos showing usage of Dependency Properties, Attached Dependency Properties and ControlTemplates in WPF.

Wednesday, September 10, 2008

Making SharpDevelop compile and debug Boo programs on a 64-bit machine

Recently I've started looking at Boo. As of now the only decent development tool for Boo is SharpDevelop. BooLangStudio, a Visual Studio plugin, recently came out in an alpha release. However, at the moment it's way too immature. Back to SharpDevelop... I'm running a 64-bit version of Vista which resulted in some problems compiling and debugging Boo programs. Since the compiler (booc.exe) is marked to run on AnyCPU it will start as a 64-bit process. SharpDevelop runs as 32-bit only. Therefore it will use the 32-bit version of MSBuild which in turn picks up a 32-bit version of System.dll and passes this version too booc.exe. Unfortunately this means that the 64-bit booc.exe process will crash when it tries to load the 32-bit System.dll. A solution to this is to use CorFlags to mark booc.exe as 32-bit only. However, this breaks the strong name so you'll have to resign it. Do the following:
  1. Open Visual Studio Command Prompt and run CorFlags "path\SharpDevelop\3.0\AddIns\AddIns\BackendBindings\BooBinding\booc.exe" /32BIT+ /Force.
  2. Download boo.snk from http://svn.codehaus.org/boo/boo/trunk/src/. Still in VS Command Prompt run sn -R "path\SharpDevelop\3.0\AddIns\AddIns\BackendBindings\BooBinding\booc.exe" "path\boo.snk".
You can now build your Boo programs!! A new problem suddenly arises when you try to debug your program. The debugger crashes because your program is compiled to run on AnyCPU. So the 32-bit only compatible debugger will launch a 64-bit program and crash. SharpDevelop suggests that you set the target cpu of your program to 32-bit. This is not possible to do; The only option is AnyCPU. So we'll have to hack some more:
  • Open the property page of your project and go to the Build Events tab. In the Post-build event command line text box type "path\Microsoft.NET\SDK\v2.0 64bit\Bin\CorFlags.exe" "$(TargetPath)" /32BIT+
Now build and debug your program. Voila!!

Monday, July 28, 2008

Balsamiq Mockups: Taking the evilness out of prototypes

Everyone that has heard Odd Helge Gravalid's presentation "Gui prototyper Onde" (GUI Prototypes Are Evil) knows why prototypes are evil shit. The main point is that proptypes create expectations about the functionality in the GUI that may not be fully implemented or may not be present at all, but it seems like it is. So what's wrong about that? Well, as I recently experienced; A couple of weeks after you presented the prototype, when you actually have implemented the functionality, the customer's project manager says: "What have you guys really been doing lately? This is nothing more than you showed me two weeks ago". And then you are in trouble. So the moral is that you should never make a prototype that actually looks like it's really implemented. It will most certainly backfire! Last Friday I came across this great GUI mockup tool called Balsamiq Mockups. The tool makes it really easy to create mockups by using the more than 60 pre-built controls. The cool thing is that it looks like they're actually drawn by hand, "so that people don't get attached to “that pretty color gradient”". This can certainly help us out not going in that prototype trap and rather let us concentrate on the important aspect of prototyping: Discussing functionality! Check it out: You can even try it out here!

70-502: WPF Exam

It's been a long time since I've blogged. What have I been up to lately? For the most part I've been working and tried to enjoy the summer as much as possible. I've also managed to pass the 70-502 - Microsoft .NET Framework 3.5 – Windows Presentation Foundation Application Development exam. For the last month and a half I've been working on a WPF project and I would recommend everyone that has done some work with WPF to give the exam a shot. It's actually quite easy.

Wednesday, April 23, 2008

Refactoring: Later? Continuously!

A couple of days ago I attended a meeting about refactoring. Some of the attendants were unfamiliar or felt unsecure about refactoring. One of the questions that arose was; "When is it time to refactor? Is it a joint descision in the developer team that it's time to refactor or is it an independent descision?" There is NEVER a special time for refactoring. You don't create a task that says refactoring. Refactoring goes hand in hand with coding and should be performed CONTINUOUSLY. ALWAYS. You should always take into account refactoring when estimating a task, if not you're in deep shit. The customers generally don't care if you build a house with duct tape, as long as it looks good enough. And they will certainly not pay for later changes not visible from the outside. But as a professional developer you know that the house will fall apart when the rainy day comes. So ALWAYS refactor and estimate accordingly!

Tuesday, April 22, 2008

DataGrid revisited

Today I held a little presentation at work showing off some of the DataGrid capabilities in Silverlight 2.0 beta. It's basically based upon my last post, but I added some new functionality that shows use of the DataGridCheckBoxColumn and the DataGridTemplateColumn.
<Data:DataGridCheckBoxColumn Header="Is done" DisplayMemberBinding="{Binding IsDone, Mode=TwoWay}" />
<Data:DataGridTemplateColumn Header="Due date">
  <Data:DataGridTemplateColumn.CellTemplate>
      <DataTemplate>
          <TextBlock Text="{Binding DueDate, Mode=TwoWay}" />
      </DataTemplate>
  </Data:DataGridTemplateColumn.CellTemplate>
  <Data:DataGridTemplateColumn.CellEditingTemplate>
      <DataTemplate>
          <DatePicker SelectedDateFormat="Short" FirstDayOfWeek="Monday" SelectedDate="{Binding DueDate, Mode=TwoWay}" />
      </DataTemplate>
  </Data:DataGridTemplateColumn.CellEditingTemplate>
</Data:DataGridTemplateColumn>
You can download the source code here