Month: June 2011

TypeMock tutorial #02. Object creation.

In this new  part of the TypeMock series I am going to show you how to deal with objects and classes in general, how you can create them and what are (honestly aren’t) the limit of TypeMock on dealing with objects.

First of all I have just drawn down a little domain that I have added to the demo application. I am planning to upload this demo the next week on Codeplex.com so that every geek reading this blog can just go there and download the source code.

The Demo domain

The domain is a very simple one, we have an abstract base class called Person, then we have two concrete classes, an Employee and a Customer that right now do not have any differences (we will see in the next tutorials why we have two different concrete classes) and then we have a value object Address that is composed only if we provide to it a parent Person object in the constructor. The Person entity exposes a read-only IEnumerable collection of Addresses, so in order to add or remove an address we must use the provided methods AddAddress and RemoveAddress.

The following picture shows the corresponding class diagram of this small domain.

ClassDiagram

These are the most important piece of code that you may be interested in:

Read-only collection Addresses
  1. private IList<Address> addresses = new List<Address>();
  2.  
  3. public IEnumerable<Address> Addresses
  4. {
  5.     get { return this.addresses; }
  6. }
  7.  
  8. public void AddAddress(Address address)
  9. {
  10.     if (this.addresses.Contains(address))
  11.     {
  12.         throw new InvalidOperationException(“The address is already in the collection.”);
  13.     }
  14.     this.addresses.Add(address);
  15. }
  16.  
  17. public void RemoveAddress(Address address)
  18. {
  19.     if (!this.addresses.Contains(address))
  20.     {
  21.         throw new InvalidOperationException(“The address is not in the collection.”);
  22.     }
  23.     this.addresses.Add(address);
  24. }

and

Constructor of an Address obj
  1. public Address(Person person)
  2. {
  3.     Person = person;
  4. }
  5.  
  6. public Person Person { get; private set; }

As you can see we have few things that need to be tested but in order to do that we have to create new instances of these objects in order to run our tests, which is pretty verbose and boring

Create the test project

The first step is to create a new Visual Studio 2010 Visual C# class library project and call it TypeMockDemo.Fixture and add the following references to it:

image

The references are pointing to:

  • my TDD framework nUnit (you can work with any TDD framework but I personally found nUnit to be the best out there …)
  • TypeMock assemblies, installed in the GAC of your machine
  • The TypeMockDemo project (the one we have the domain entities in)

Now we can start to create the first class fixture and verify that we can create a new Person, a new Employee and a new Customer. But hold on a second! How can we mock an abstract and two sealed class with a mocking framework? We simply can’t if we are not using TypeMock … Winking smile

Create new abstract and Sealed
  1. [Test]
  2. [Category(“Domain.Isolated”)]
  3. public void AssertThatCanCreateANewPerson()
  4. {
  5.     Person person = Isolate.Fake.Instance<Person>();
  6.     Assert.That(person, Is.Not.Null);
  7. }
  8.  
  9. [Test]
  10. [Category(“Domain.Isolated”)]
  11. public void AssertThatCanCreateANewEmployee()
  12. {
  13.     Person person = Isolate.Fake.Instance<Employee>();
  14.     Assert.That(person, Is.Not.Null);
  15. }
  16.  
  17. [Test]
  18. [Category(“Domain.Isolated”)]
  19. public void AssertThatCanCreateANewCustomer()
  20. {
  21.     Person person = Isolate.Fake.Instance<Customer>();
  22.     Assert.That(person, Is.Not.Null);
  23. }

Looking at the code we have introduced the new method Isolate.Fake.Instance<T> that is coming from TypeMock. With this method we can simply inform TypeMock that we want it will create for us a Proxy of the object we want to mock and it will return a derived class of the tested one, even if we are mocking a sealed class.

If the class is sealed TypeMock will create a new instance of the original object while if the object is abstract, TypeMock will create a proxy version of that object. Same thing will be done for all the child properties, complex or not …

image

That’s simply wow, we just used two lines of code to create a mockup and test it.

Now let’s move forward and let’s verify that we will not be able to add the same address twice and to remove the same address twice from a Person object.

Working with Instances or Proxy?

First of all we start to create this simple test but the result is not the one we expect …

Test a collection
  1. [Test]
  2. [Category(“Domain.Isolated”)]
  3. public void AssertThatCanAddTheSameAddressTwice()
  4. {
  5.     Person person = Isolate.Fake.Instance<Person>();
  6.     Address address = Isolate.Fake.Instance<Address>();
  7.     person.AddAddress(address);
  8.     Assert.That(person.Addresses.Count(), Is.EqualTo(1));
  9.     Assert.Throws<InvalidOperationException>(() => person.AddAddress(address));
  10. }

nUnit bombs saying that at line 8 the expected result is supposed to be 1 but in reality is 0. Why? This happens because TypeMock has created a full mockup proxy of the person object so also the methods AddAddress and RemoveAddress are mocks and they do not point to the real code we have implemented …

Control the creation
  1. [Test]
  2. [Category(“Domain.Isolated”)]
  3. public void AssertThatCanAddTheSameAddressTwice()
  4. {
  5.     Person person = Isolate.Fake.Instance<Person>(Members.CallOriginal, ConstructorWillBe.Called);
  6.     Address address = Isolate.Fake.Instance<Address>();
  7.     person.AddAddress(address);
  8.     Assert.That(person.Addresses.Count(), Is.EqualTo(1));
  9.     Assert.Throws<InvalidOperationException>(() => person.AddAddress(address));
  10. }

If we change the way TypeMock is creating the object Person, we can now say to it:

Dear TypeMock, I want that you create an instance of my object and that you call its constructor so that I can test the code I have implemented in this abstract class …

Et voila’, the test will pass! Same thing for the remove address and so on …

Now, the last test we may require is that we want to be sure that when we create a new address, the constructor is properly injecting the parent Person object so that we can keep a back-forward reference from the parent object and the collection of children.

Test injection in constructor
  1. [Test]
  2. [Category(“Domain.Isolated”)]
  3. public void AssertThatWhenCreateAnAddressTheParentPersonIsInjected()
  4. {
  5.     Person person = Isolate.Fake.Instance<Person>(Members.CallOriginal, ConstructorWillBe.Called);
  6.     Address address = Isolate.Fake.Instance<Address>();
  7.     Assert.That(person, Is.Not.Null);
  8.     Assert.That(address, Is.Not.Null);
  9.     Assert.That(address, Has.Property(“Person”).EqualTo(person));
  10. }

We run the test and kabum! It fails again. This time it fails on the address side because the Person instance TypeMock is injecting is not the same it returned to use in the previous line of code. So what can we do now?

We can manually create an Address and inject the parent Person but it sucks … or we can do this:

Customize constructor
  1. [Test]
  2. [Category(“Domain.Isolated”)]
  3. public void AssertThatWhenCreateAnAddressTheParentPersonIsInjected()
  4. {
  5.     Person person = Isolate.Fake.Instance<Person>(Members.CallOriginal, ConstructorWillBe.Called);
  6.     Address address = Isolate.Fake.Instance<Address>(Members.CallOriginal, ConstructorWillBe.Called, person);
  7.     
  8.     Assert.That(person, Is.Not.Null);
  9.     Assert.That(address, Is.Not.Null);
  10.     Assert.That(address, Has.Property(“Person”).EqualTo(person));
  11. }

 

We simply inject the person value we want to use (the one created by TypeMock) because this is what it is going to happen with live code. What we care here is to be sure that inside the Address class constructor, the Person parameter is passed to the read-only property Person of the Address class, nothing more, nothing less!

Conclusion

As you can see, TypeMock is pretty cool and it allows you to control the way we can create and fake objects. Even if we use proxies we can still ask to TypeMock to create a real mock that reflect our code so that we can still test the business logic included in our objects without the need of creating complex objects manually.

If you want to read more about this topic I kindly suggest you this:

In the next tutorial we will see how to customize the methods and other behaviors of an object and I will also publish the first part of the quiz that will allow you to win almost 1,000 USD value of TypeMock license!

Stay tuned

A Devil in the house …

Just a little OT to keep you up to date also about my private life (if anyone of you cares … Winking smile).

Last Friday we got a new member in our family, after we lost our precious Doberman after 10 years, we decided to move forward and forget the drama by getting a new dog. This time we bought a Jack Russell Terrier … what a Devil!

Her name is Sophie, she is now 3 months old and she is the alpha of her litter … so a little bit a “devil dog”. Really energetic and with a strong character! A nice challenge for me and my wife.

The first thing we want to teach her is to jump on a surf board and surf! I will publish a video of her soon.

For now, enjoy this:

TypeMock tutorial #01. Startup.

The best way to learn a tool is to try it, test it and then finally use it over your code. Of course if the tool provides also a great community support and a great documentation the task will be easier.

Some weeks ago we started to adopt a wonderful tool to create mockups and other TDD fancy stuff, the tool is TypeMock.

The idea I got is to create a series of tutorials about TypeMock and provide to you a piece of a code to download a full license of this tool. At the end of the series (probably 1 month) you will be able to enable your 10 days trial into a full working license. I will create a sort of bid and from all my readers that will contact me to get the license I will come up with one or two free licenses.

Guys, consider that one license of TypeMock is 800 $ !!

Setup and Installation

In order to start right away with TypeMock you need to download the latest version of the tool (at this time they have the version 6.0.10) but be careful because they upload new versions often. The product you need to download for .NET is Isolator.NET. They also provide additional tools that we will analyze during this series, like:

  • TestDriven.NET, an integrated test runner for Visual Studio
  • Isolator for Sharepoint
  • Isolator for ASP.NET and ASP.NET MVC
  • TeamMate, a useful tool to monitor your TDD approach
  • Isolator ++, the same version but for C++
  • TestLint, a nice tool that will help you to develop your TDD skill

and more.

After you have downloaded the setup (7 Mb) you will have to follow a very straightforward setup wizard with only two options available; use the advanced option and install everything including the samples for .NET.

That’s it, you are now ready to go!

File Location

TypeMock is installed on your C:\ drive and depending on where you choose to install it, you should have a folder called TypeMock/Isolator/6.0 on your Program Files directory. Inside this folder you can find all the assemblies available from TypeMock.

You do not need to use them directly as TypeMock is also installed on your GAC folder but if you plan to work with C.I. (Continuous Integration) you may probably need to add a reference to these files instead of pointing directly to the GAC, depending on what type of build server you are working with … Winking smile

Inside the folder Examples you will find a set of useful examples to start to learn TypeMock quickly but do not worry as I will go through all these examples in this series.

If you want to make your experience with TypeMock easier and smoother, I kindly suggest you to download and install also TestDriven.NET or Resharper with Gallio. I personally use and love Resharper so you will find in this series all the reference examples pointing to the Resharper UI inside Visual Studio. The choice is up to you but I personally believe R# is the best tool so far for Visual Studio (IMHO)

Visual Studio integration

After the installation you can open Visual Studio and this is the surprise you will find in the IDE:

Screen shot 2011-06-13 at 11.56.00 PM You will find a new menu on Visual Studio called TypeMock; in this menu you can setup the license, the profiler to use with TypeMock and few other options for a better Visual Studio experience.

There aren’t a lot of other ways to easily configure TypeMock but we will see together how you can tackle each of the common tasks you may encounter while working with TypeMock.

From this menu you have also the easy option of enabling/disabling TypeMock at anytime so that you can or cannot work with it without the need to restarting Visual Studio every time (like you have to do with other plugins of Visual Studio).

The Demo Project

I have created a very small project for this series of tutorials to show you how you can test every single layer of a .NET application using TypeMock to separate the dependencies. The structure of the demo project is in the following way:

Screen shot 2011-06-19 at 4.26.58 PM

The project is composed by 4 different layers:

  1. TypeMockDemo: the project that contains the Domain Model of the tutorial
  2. TypeMockDemo.DataLayer: a data layer built around NHibernate 3.2
  3. TypeMockDemo.ServiceLayer: the service layer used to write the business logic around the domain and the data layer
  4. TypeMockDemo.UserInterface: an application developed using WPF 4.

 

 

For each project there is a corresponding “fixtures” project that includes all the fixtures related to the project. With fixture I mean “test” … Winking smile

Tutorials and resources

Before starting to follow this series I kindly suggest you to have a look at the TypeMock web site learning content, so that you will follow better my tutorials. As you know, I do not usually go too deep into a specific topic, so if you need to learn also what TDD is, I kindly suggest you to read also the following tutorials about TDD and testing in general.

TypeMock learning content:

TDD learning content:

 

So stay tuned and I’ll see you next Friday for the next part of this series.

New content for my Microsoft book

The Microsoft’s book I have published few months ago: “Building Enterprise Applications with WPF and MVVM” has been a success but I still got some negative feedbacks that me and my editor we want to get rid off.

This book is my first real book and of course it was my first experience on writing a book (for this reason we kept the price of the book very low). Anyway .. I got some bad feedbacks about missing parts, parts not explained as expected and a misunderstanding of the book audience and target.

I personally believe that the biggest problem is in the title of book, it drives you a little bit out of the topic of the book, if you buy this book you will believe to get the “bible to LOB applications with MVVM”, which is not.

For this reasons and also to keep high the audience of the book, we have decided to deliver for free new additional content for the book! Open-mouthed smile

The list of the new content is still under discussion with my editor but this is a rough list of the topics I will touch or expand in this new context that should be composed by 3 additional chapters!

  • Design patterns
    I am planning to add 20/30 additional pages on the second chapter in order to exhaustively cover everything related to the most known design patterns
  • Advanced MVVM
    I will add a new chapter where I will explain some “well known” problems you may find when the adoption of the MVVM pattern starts to get tricky!
  • Composite Frameworks for MVVM in practice
    In this chapter we will build the same Master-Detail UI logic using the three most famous frameworks for WPF/Silverlight: PRISM, Caliburn and Light Toolkit

If you believe that the book is still missing other information, feel free to send me an e-mail and I will be glad to discuss this with my editor.

Note: Remember also that we are planning to distribute the source code of the book as an Open Source project on Codeplex.com before the end of the year.

Hope this will help!

Unity and injection with factories.

Last week in the office I just found a bug on how I was implementing a series of Inversion of Control chain using Microsoft Unity. To be precise, the bug has been found by one of the new guy in the team, Gary McLean Hall, the author of the book “APRESS – Pro WPF and Silverlight MVVM”.

Before starting with the explanation of the problem, let’s see what I am talking about. I believe that anyone of you know already concepts like “Inversion of Control” and ‘Dependency Injection”; if you don’t, just follow the links. Winking smile

A classic injection mechanism.

A classic mechanism of IoC is the one used by the Unit of Work and Repository patterns, where a repository can’t exist without an injected unit of work able to control the transaction. So, in order to have such a kind of example, I have implemented a simple data layer that shows you these dependencies:

image

Now, for these two contracts we will need to concrete implementations like the following classes:

image

And the final touch will be the implementation. Now, I am not going to implement a full data layer in this post as it is not the target of this writing, instead I want to show you how to “inject” a unit of work …

Repository constructor
  1. using System;
  2. using System.Linq;
  3.  
  4. namespace InversionOfControl_dynamic
  5. {
  6.     public sealed class Repository : IRepository
  7.     {
  8.         #region IRepository Members
  9.  
  10.         public void Create<T>(T entity)
  11.         {
  12.             this.unitOfWork.MarkNew(entity);
  13.         }
  14.  
  15.         /// IRepository implementation removed to save space …
  16.  
  17.         #endregion
  18.  
  19.         #region Injection of the Unit of Work
  20.  
  21.         private IUnitOfWork unitOfWork;
  22.  
  23.         public Repository(IUnitOfWork unitOfWork)
  24.         {
  25.             this.unitOfWork = unitOfWork;
  26.         }
  27.  
  28.         #endregion
  29.  
  30.     }
  31. }

Now we can easily register the components with Unity and verify that when we call a Repository class, we are injecting a new Unit of Work using Unity.

The following test is accomplishing this task:

TDD the injection process
  1. [TestFixture]
  2. public sealed class StandardFixture
  3. {
  4.     private IUnityContainer container;
  5.  
  6.     [TestFixtureSetUp]
  7.     public void InitializeTests()
  8.     {
  9.         container = new UnityContainer();
  10.         container.RegisterType<IUnitOfWork, UnitOfWork>();
  11.         container.RegisterType<IRepository, Repository>();
  12.     }
  13.  
  14.     [Test]
  15.     public void Assert_That_Unity_Can_Resolve_Dependency()
  16.     {
  17.         IRepository repository = container.Resolve<IRepository>();
  18.         Assert.That(repository, Is.Not.Null);
  19.         Assert.That(repository, Is.InstanceOf<Repository>());
  20.         // Here I have created a public read-only property
  21.         // for testing purposes
  22.         Assert.That(repository, Has.Property(“UnitOfWork”).Not.Null);
  23.     }
  24. }

So far so good. The only missing part here is the last statement (line 22) of the code. Here I have created a read-only IUnitOfWork property, only in the concrete Repository class, in order to test that the IUnitOfWork is injected properly.

Injecting using factory

Now, let’s assume for a second that the previous approach is not valid; it is not valid because we are not in charge of creating an IUnitOfWork by our self. We need a factory that will create the contract for use.

So, first of all, I am going to create a simple factory that will return, with a static method, an instance of an IUnitOfWork object.

Unit of Work Factory
  1. public sealed class Factory
  2. {
  3.     public static IUnitOfWork GetUnitOfWork()
  4.     {
  5.         return new UnitOfWork();
  6.     }
  7. }

Now we are screwed because the previous approach does not work anymore… Green with envy If I want to create a new instance of a repository I need to inform Unity, somehow, that it needs to call this method of the factory to create a new instance of an IUnitOfWork. But how?

We found the class InjectionFactory ables to specify a delegate for the creation of a new object, like this code:

InjectionFactory declaration
  1. container = new UnityContainer();
  2. container.RegisterType<IUnitOfWork>(new InjectionFactory(c =>
  3.     Factory.GetUnitOfWork()));
  4. container.RegisterType<IRepository, Repository>();

Now we can simply assert that when we create two instance of an IRepository interface using Unity, it will return two different instances of the IUnitOfWork object:

Code Snippet
  1. [Test]
  2. public void Assert_That_Unity_Can_Resolve_Dependency()
  3. {
  4.     var currentRepository = container.Resolve<IRepository>();
  5.     var currentUoW = currentRepository.GetType().GetProperty(“UnitOfWork”).GetValue(currentRepository, null);
  6.  
  7.     var expectedRepository = container.Resolve<IRepository>();
  8.     var expectedUoW = currentRepository.GetType().GetProperty(“UnitOfWork”).GetValue(expectedRepository, null);
  9.  
  10.     Assert.That(currentUoW, Is.Not.Null);
  11.     Assert.That(expectedUoW, Is.Not.Null);
  12.  
  13.     Assert.That(currentUoW, Is.Not.EqualTo(expectedUoW));
  14. }

If you want to read more about this object and other way of customizing the way Unity allows you to register objects, you can have a look at this section of MSDN:

Happy IoC to everybody!

Open-mouthed smile

Applied WPF in context is out.

During the last two months I have been away from Bermuda and I didn’t have a lot of time to write or post any news on this blog.

In the meantime, I didn’t realize that my new book from APRESS: “Applied WPF 4 in context” has been published so it is time to post some info about it.

The cover of the book is following the APRESS new style and it is the following one:

APRESS_cover

The new series “applied in context” of APRESS deliver content by example and practical code, so in this book you will realize a full working WPF 4 application using all the available tools of Microsoft like: Visual Studio 2010, Expression Blend 4 and SQL Server 2008 R2.

Who this book is for?

This book is for Windows application developers who want to understand the context in which WPF sits and the standards and best practices that can be employed to improve the efficiency and maintainability of their projects. This book can be used by a junior developer to learn WPF and understand how to architect a layered application, and it can be used also by a senior developer as a reference for developing scalable WPF applications.

Table of content.

Following is the table of content of the book:

  1. Introducing WPF and XAML
  2. Sample Application: Overview and Getting Started
  3. Microsoft Expression Blend
  4. Creating the Views
  5. Adding Controls to the Views
  6. The Entity Framework
  7. Data Binding
  8. Command Handling and Event Routing
  9. Testing with TDD   
  10. Reports with Microsoft Reporting Services
  11. Deploying the Application Using ClickOnce
  12. Design Patterns in WPF
  13. WPF and Multi-Threading
  14. Interacting with WCF

Distributors.

The book is released and published by APRESS so in this case the book can be bought from the APRESS web site or from one of their distributors. Right now, Amazon has already run out of copies so you should expect the next distribution starting the 7th of June for the Paperback copy. You can still download the e-book from Amazon.com or APRESS. I am not sure I will distribute this book also with Kindle as I had some issues with the previous one so for now it won’t be available directly in the Kindle web site or in the iBook application for iPad.

Right now you can buy the book here:

The are also other distributors that I do not personally follow but I believe that buying the book directly from APRESS will give you the best price/availability options.

Prices.

This is the list of the official prices, if you find the book with a different price from a different distributor than the one listed in the previous section I am not aware about it, so please let me know if you believe someone is distributing the book with a non fair price.

Print version with shipment from APRESS including TAX: 49.99 USD

E-book version from APRESS including TAX: 34.99 USD

Enjoy and as usual, let me know what you think about it! Hot smile