Saturday, October 24, 2009

An AAA style BDD specification base class

Lately I have written a lot of Arrange, Act, Assert style tests using Rhino Mocks. I’ve also started to write more readable tests with a dash of BDD style naming like this:

[Fact]
public void Should_find_projects_when_user_searches()
{
 //Arrange
 var projectRepository = MockRepository.GenerateMock<IProjectRepository>();
 var projects = new List<Project> { ProjectMother.CreateProject("project 1"), ProjectMother.CreateProject("project 2") };
 projectRepository.Stub(me => me.FindByName(null)).IgnoreArguments().Return(projects);
 var presentationModel = new ProjectSearchPresentationModel(projectRepository);
 //Act
 presentationModel.SearchCommand.Execute("");
 //Assert
 projectRepository.AssertWasCalled(me => me.FindByName(""));
 Assert.Equal(projects.Count, presentationModel.Projects.Count);
}

The scenario for this test is “When the user searches”. If we look closely we see that it have two asserts. When the user searches it should ask the repository for projects and the result should be “displayed” in a list. This feels a bit odd. I have to create a name for the test that captures everything that has to be done when the user searches. This is hard and I’m likely to loose some of the intent. The solution is to split the test in a test for every assert. However, this means that I have to set up each test in an equal manner and call the serach command. This is DRY! To solve this I’ve created a test base class called Specification that enables me to write the above test like this:

namespace Specifications_for_project_search_presentation_model
{
 public class When_user_searches_for_projects : Specification
 {
     private ProjectSearchPresentationModel _presentationModel;
     private List<Project> _projects;
     private IProjectRepository _projectRepository;

     public override void Arrange()
     {
         _projectRepository = MockRepository.GenerateMock<IProjectRepository>();
         _projects = new List<Project> { ProjectMother.CreateProject("project 1"), ProjectMother.CreateProject("project 2") };
         _projectRepository.Stub(me => me.FindByName(null)).IgnoreArguments().Return(_projects);
         _presentationModel = new ProjectSearchPresentationModel(_projectRepository);
     }

     public override void Act()
     {
         _presentationModel.SearchCommand.Execute("");         
     }

     [Fact]
     public void should_search_repository()
     {
         _projectRepository.AssertWasCalled(me => me.FindByName(""));         
     }

     [Fact]
     public void should_show_result()
     {
         Assert.True(_presentationModel.CanShowProjects);
     }

     [Fact]
     public void should_list_projects_found()
     {
         Assert.Equal(_projects.Count, _presentationModel.Projects.Count);
     }
 }
}

I have now set up the context and called the search command only once, but have a seperate test for each assert. I think these kind of tests read nicely. I have a test class for each scenario and tests that reads like the specification for the scenario. This also look very good in ReSharper.

specifications

The base class is implemented like this for xUnit:

public abstract class Specification
{
 protected Specification()
 {
     Arrange();
     Act();
 }

 public abstract void Arrange();
 public abstract void Act();
}

Tuesday, June 9, 2009

.NET RIA Services is for RAD only!

A bit late to comment, but .NET RIA Services was announced at MIX09. I recently spent some minutes to see what the fuzz was all about.

.NET RIA Services is a framework proclaimed for Line of Business development which is supposed to make it easy to build N-tier application. The framework makes it easy to expose your domain logic on the server to the client, with validation, authorization, querying and so on. You do this by defining a DomainService like this (taken from the RIA Services Overview):

[EnableClientAccess()]
public class CityService : DomainService
{
  private CityData _cityData = new CityData();
  public IEnumerable<City> GetCities()
  {
      return _cityData.Cities;
  }
}
The EnableClientAccess attribute exposes proxies of your entities to the client by code generation. It also generates client access to your operations.

Sounds intriguing? Not really. I wouldn’t have an enterprise application rely so much on magic, but hey, it could maybe be done..

As you can see from the service, an entity called City is exposed to client:

public partial class City
{
  [Key]
  public string Name { get; set; }
  [Key]
  public string State { get; set; }
}

Why is the class partial you wonder..? As I said the framwork lets you validate your domain logic both on the server and client. To be able to do this you have to create a metadata class, also known as a buddy class:

[MetadataType(typeof(CityMetadata))]
public partial class City
{
  internal sealed class CityMetadata
  {
      [Required]
      public string Name;

      [Required]
      [StringLength(2, MinimumLength = 2)]
      public string State;
  }
}
Metadata classes provide a way to attach metadata to an entity without actually modifying the corresponding members on the entity itself. When you generate the client proxy you also get the validation attributes. Sounds intriguing? Not in my wildest dreams. To get validation you actually have to repeat every property of City. This is as DRY as it can possible get. Add the shared code functionality to the soup and you have yourself a maintainability nightmare. .NET RIA Services is for RAD only; prototypes and applications that never reach a satisfactory production quality. I would never ever use this in a production system.

Thursday, February 12, 2009

WPF and the Presentation Model Pattern

Over the last 6 months I've been working on a several projects where we have used Windows Presentation Foundation as our technology for creating GUI. When we started I began looking for presentation pattern that would best utilize the Data Binding capabilities in WPF and and at the same time could best interact with my domain model. In search for a suitable pattern I came across the Presentation Model by Martin Fowler. The Presenation Model, aka Application Model, aka Model-View-ViewModel pattern pulls the state and behavior of the view out into a model class that is part of the presentation layer. Since the presentation model holds the data that the view is going to render, there needs to be some kind of synchronization between the two. Based on the behaviour of the view, the presentation model changes it's state and automatically updates the view through Data Binding.

guiarch One can look at the view as a projection of the data in the Presentation Model. The Presentation Model has poperties for the information in the view and properties for state, typically disabling/enabling of buttons based on the current state of the view. The Presentation Model interacts with and updates the domain model through its properties. The following code illustates a typical presentation model for a project search view (in the context of my standard scrum application):

public class ProjectSearchPresentationModel : PresentationModel
{
private List<Project> mProjects = new List<Project>();
private DelegateCommand<string> mSearchCommand;

private DelegateCommand<Project> mSelectCommand;

public DelegateCommand<string> SearchCommand
{
 get
 {
     if (mSearchCommand == null)
         mSearchCommand = new DelegateCommand<string>(FindProjects);
     return mSearchCommand;
 }
}

public DelegateCommand<Project> SelectCommand
{
 get
 {
     if (mSelectCommand == null)
         mSelectCommand = new DelegateCommand<Project>(SelectProject);
     return mSelectCommand;
 }
}

public List<Project> Projects
{
 get { return mProjects; }
 set
 {
     mProjects = value;
     this.Notify(() => Projects);
     this.Notify(() => CanShowProjects);
 }
}

public bool CanShowProjects
{
 get { return Projects.Count() > 0; }
}

public void FindProjects(string searchText)
{
 var repository = IoC.Get<IProjectRepository>();
 Projects = repository.Query(project => project.Name == searchText);
}


public void SelectProject(Project project)
{
 ApplicationController.Instance.SelectProject(project);
}

public override void Refresh()
{
}
}
In the code behind of my view I instantiate a new ProjectSearchPresentationModel and set the DataContext of the view to my presentation model object:
public partial class ProjectSearchView : IView
{
private PresentationModel mPresentationModel;

public void Init()
{
 InitializeComponent();
 mPresentationModel = new ProjectSearchPresentationModel();
 DataContext = mPresentationModel;
}
}
The view now binds to the Projects property of the ProjectSearchPresentationModel and displays a list of Project objects based on the search criteria:
<StackPanel>
<Label Content="Enter customer name" />
<StackPanel Orientation="Horizontal">
 <TextBox Name="searchText" Width="100" />
 <Button Command="{Binding .SearchCommand}" CommandParameter="{Binding Text, ElementName=searchText}" Margin="5,0,0,0" Content="Search" />
</StackPanel>
</StackPanel>

<ListView Grid.Row="1" ItemsSource="{Binding .Projects}" Visibility="{Binding .CanShowProjects, Converter={StaticResource boolConverter}}">
<ListView.View>
 <GridView>
     <GridViewColumn Header="Action">
         <GridViewColumn.CellTemplate>
             <DataTemplate>
                 <Label>
                     <Hyperlink Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type Views:IView}}, Path=DataContext.SelectCommand}" CommandParameter="{Binding .}">Select</Hyperlink>
                 </Label>
             </DataTemplate>
         </GridViewColumn.CellTemplate>
     </GridViewColumn>
     <GridViewColumn Header="Name">
         <GridViewColumn.CellTemplate>
             <DataTemplate>
                 <Label Content="{Binding .Name}" />
             </DataTemplate>
         </GridViewColumn.CellTemplate>
     </GridViewColumn>
 </GridView>
</ListView.View>
</ListView>
Note that I’m not using any event handlers in the code behind of the view. Instead I’m binding to Command properties defined in the ProjectSearchPresentationModel, which is hooked up to methods in the presentation model:
<Button Command="{Binding .SearchCommand}"
 CommandParameter="{Binding Text, ElementName=searchText}"
 Margin="5,0,0,0"
 Content="Search" />
public DelegateCommand<string> SearchCommand
{
get
{
 if (mSearchCommand == null)
     mSearchCommand = new DelegateCommand<string>(FindProjects);
 return mSearchCommand;
}
}

public void FindProjects(string searchText)
{
var repository = IoC.Get<IProjectRepository>();
Projects = repository.Query(project => project.Name == searchText);
}
The generic DelegateCommand is a class that implements the ICommand interface and is similar to the DelegateCommand found in the Prism framework. With commands I can keep the code behind of the view almost free from code. In my opinion the Presentation Model pattern is extremely powerful in combination with WPF. I find it both effective and easy to work with and lets me seperate the view from the domain model in an elegant way, which in turn makes it easy to test the view. This is how I do it. Stay tuned for more!

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!