Category: TDD

Do you Test your applications?

When I talk about test with a collegue, a tech friend or anybody involved in Software Development, the conversation always ends up with a comparison between Unit Tests and Integration Tests. As far as I am aware of, I know four type of developers, the one that practices unit tests, the once that practices integration tests, the one that practices both and the one that doesn’t practice any test at all …

In my opinion just the fact that we compare the two techniques means that we don’t really apply the concept of test in our applications. Why? To make it more clear, let’s have a look at what is a Unit Test and what is an Integration Test, but also what is a Validation Test.

Unit Test
From Wikipedia: A unit test is a test for a specific unit of source code, it is in charge of proving that the specific unit of source code is fit for the use.

Integration Test
From Wikipedia: An integration test is a test that proves that multiple modules, covered by unit tests, can work together in integration.

Validation Test
From Wikipedia: A validation test is a test that proves that the entire application is able to satisfy the requirements and specifications provided by the entity who requested the application (customer).

We have three different type of tests for an application. They are quite different and indipendent from each other and in my opinion you can’t say an application “is working” only because you achieved 100% code coverage or because you have a nice set of Behavioral tests. You can say that your application is tested if:

The modules are created using TDD so that we know the code is 100% covered, then those modules are tested to work together in a “real environment, finally we should also verify that our result is the one expected by the customer.

An architecture to be tested

As a Software Architect I need to be sure that the entire architecture I am in charge of, is tested. This means that somehow, depending on the team/technology I am working with, I need to find a solution to test (unit, integration and validation) the final result and feel confident.

What do I mean with feel confident? I mean, I should be confident when the build is green that I can go to my Product Owner or Product Manager and says “Hey, a new release is available!”.

So, as usual for my posts, we need a sample architecture to continue the conversation.


Here we have a classic multi-layer architecture, where we have the data, the data acces, the business logic and the presentation layer, logically separated. We can consider each layer a separate set of modules that need to speak to each other.

How do we test this?
In this case I use a specific pattern that I developed during the years. First, each piece of code requires a unit test, so that I can achieve the first test requirement, the unit test requirement. Then I need to create a test environment where I can run multiple modules together, to test the integration between them. When I am satisfied with these two typologies of tests, I need a QA that will verify the final result and achieve also the validation test.

Below I have just created an example of the different type of tests that I may come up with in order to be able to test the previosuly described architecture.

Unit Tests

First of all, the unit test. The unit test should be spreaded everywhere and achieve always the 100% code coverage. Why? Very simple, the concept behind TDD is to “write a test before write or modify a piece of code”; so if you code in this way, you will always have 100% code coverage … In the same way if you don’t achieve 100% code coverage, you are probably doing something wrong

Considering now our data layer, for example, I should have the following structure into my application. A module per context with a correspondent test module :


This is enough to achieve 100% code coverage and comply to the first test category: unit test.

Integration Tests

Now that the functionalities are implemented and covered by a bunch of unit tests, I need to design and implement a test environment, an environment where I can deploy my code and test it in integration mode.

The schema below shows how I achieve this using Microsoft NET and the Windows platform. I am quite sure you can achieve the same result on a Unix/Linux platform and on other systems too.


In my case this is the sequence of actions triggered by a check-in:

  • The code is sent to a repository (TFS, Git, …)
  • The code is build and:
    • Unit tested
    • Code covered analysis
    • Code quality and style analysis
  • Then the code is deployed to a test machine
    • The database is deployed for test
    • The web tier is deployed for test
    • The integration tests are executed and analyzed

This set of actions can make my build green, red or partial green. From here I can decide if the code needs additional reviews or it can be deployed to a staging environment. This type of approach is able to prove that the integration between my modules is working properly.

Finally, validate everything with someone else

Now, if I got lucky enough I should have a green build, that in my specific case it is deployed in automation to a repository available on the cloud. In my specific case I use TFS Preview service and for the virtual machines I am using Azure Virtual Machines. Everything is deployed using some automation tools like Octopus Deploy, which allows me to automatically scripts all the steps required for my integration tests and for my deployment steps.

The same tool is used by the Product Owner to automate the QA, Staging and Production deployment of the final product. The interface allows you to select the version and the environment that needs to be upgraded or downgraded:

I can choose to “go live”, “go live and test” and many more options, without the needs to manually interact with the deployment/test process.

So, if you are still following me, the real concept of test is expressed only when you can easily achieve all the three phases of the test process: unit, integration and validation. The picture below represents the idea:


Hope it makes sense.

Domain Model in Brief

This series is getting quite interesting so I decided to post something about Domain Model. Just a little introduction to understand what is and what is not Domain Model.

Honestly this pattern is often misunderstood. I see tons of examples of anemic models that reflect 1:1 the database structure, mirroring the classic Active Record pattern. But Domain Model is more than that …

Let’s start as usual with a definition, and we take this definition from one of the founder of the Domain Model pattern, Martin Fowler:

An object model of the domain that incorporates both behavior and data.

But unfortunately I almost never see the first part (behaviors). It’s easy to create an object graph, completely anemic, and then hydrate the graph using an ORM that retrieves the data from the database; but if we skip the logical part of the object graph, we are still far from having a correct Domain Model.

This means that we can have anemic objects that represent our data structure, but we can’t say that we are using Domain Model.

Our Domain Model

In order to better understand the Domain Model pattern we need a sample Domain, something that aggregates together multiple objects with a common scope.

In my case, I have an Order Tracking System story that I want to implement using the Domain Model pattern. My story has a main requirement:

As a Customer I want to register my Order Number and e-mail, in order to receive updates about the Status of my Order

So, let’s draw few acceptance criteria to register an Order:

  • An Order can be created only by a user of type Administrator and should have a valid Order id
  • An Order can be changed only by a user of type Administrator
  • Any user can query the status of an Order
  • Any user can subscribe and receive updates about Order Status changes using an e-mail address

If we want to represent this Epic using a Use Case diagram, we will probably end up with something like this:


Great, now that we have the specifications, we can open Visual Studio (well I did it previously when I created the diagram …) and start to code. Or better, start to make more investigations about our Domain objects.

It’s always better to have an iteration 0 in DDD when you start to discover the Domain and the requirements together with your team. I usually discover my Domain using mockups like the following one, where I share ideas and concepts in a fancy way.


Create a new Order

An Agent can created an Order and the Order should have a proper Order Id. The order id should reflect some business rules so it’s ok to have this piece of validation logic inside our domain object. We can also say that the Order Id is a requirement for the Order object because we can’t create an Order object without passing a valid Order Id. So, it makes absolutely sense to encapsulate this concept into the Order entity.

A simple test to cover this scenario would be something like this:

public void OrderInitialStateIsCreated()
        .Given(s => s.GivenThatAnOrderIdIsAvailable())
        .When(s => s.WhenCreateANewOrder())
        .Then(s => s.ThenTheOrderShouldNotBeNull())
            .And(s => s.TheOrderStateShouldBe(OrderState.Created))
        .BDDfy("Set Order initial Status");


If you don’t know what [Fact] is, it is used by xUnit, an alternative test framework that can run within Visual Studio 2013 test runner using the available nuget test runner extension package.

From now on, we have our first Domain Entity that represents the concept of Order. This entity will be my Aggregate root, an entity that bounds together multiple objects of my Domain, in charge of guarantee consistency of changes made to those objects.

Domain Events

M. Fowler defines a Domain event in the following way:

A Domain event is an event that captures things in charge of changing the state of your application

Now, if we change the Order Status we want to be sure that an event is fired by the Order object, which inform us about the Status change. Of course this event will not be triggered when we create a new Order object. The event should contains the Order Id and the new Status. In this way we will have the key information for our domain object and we may not be required to repopulate the object from the database.

public void SetState(OrderState orderState)
    state = orderState;
    if(OrderStateChanged != null)
        OrderStateChanged(new OrderStateChangedArgs(this.orderId, this.state));

Using the Domain Event I can easily track the changes that affect my Order Status and rebuild the status in a specific point in time (I may be required to investigate the order). In the same time I can easily verify the current status of my Order by retrieving the latest event triggered by the Order object.

The ubiquitous language

With my Order object create, I need now to verify that the behaviors assigned to it are correct, and the only way to verify that is to contact a Domain expert, somebody expert in the field of Order Tracking System. Probably witht this person I will have to speak a common language, the ubiquitous language mentioned by Eric Evans.

With this language in place, I can easily write some Domain specifications that guarantee the correctness of the Domain logic, and let the Domain Expert verifies it.


This very verbose test, is still a unit test and it runs in memory. So I can easily introduce BDD into my application without the requirement of having an heavy test fitness behind my code. BDDfy allows me to produce also a nice documentation for the QA, in order to analyze the logical paths required by the acceptance criteria.

Plus, I am not working anymore with mechanical code but I am building my own language that I can share with my team and with the analysts.

Only an Administrator can Create and Change an Order

Second requirement, now that we know how to create an Order and what happen when somebody changes the Order Status, we can think of creating an object of type User and distinguish between a normal user and an administrator. We need to keep this concept again inside the Domain graph. Why? Well, very simple, because we choose to work with the Domain Model pattern, so we need to keep logic, behaviors and data within the same object graph.

So, the requirements are the following:

  • When we create an Order we need to know who you are
  • When we change the Order status, we need to know who you are

In Domain Driven Design we need to give responsibility of this action to somebody, that’s overall the logic that you have to apply when designing a Domain Model. Identify the responsibility and the object in charge of it.

In our case we can say to the Order object that, in order to be created, it requires an object of type User and verify that the user passed is of type Administrator. This is one possible option, another one could be to involve an external domain service, but in my opinion is not a crime if the Order object is aware of the concept being an administrator.

So below are my refactored Behavior tests:


The pre-conditions raised in the previous tests:

  • order id is valid
  • user not null
  • user is an administrator

are inside my Order object constructor, because in DDD and more precisely in my Use Case, it doesn’t make any sense to have an invalid Order object. So the Order object is responsible to verify the data provided in the constructor is valid.

private Order(string orderId, User user)
       .Contains("-","The Order Id has invalid format");
       .IsNotNull("The User is null");
       .IsTrue("The User is not Administrator");

    this.orderId = orderId;

Note: for my assertions I am using a nice project called Conditions that allows you to write this syntax.

Every time I have an Order object in my hands I know already that is valid, because I can’t create an invalid Order object.

Register for Updates

Now that we know how to create an Order we need to wrap the event logic into a more sophisticated object. We should have a sort of Event broker also known as Message broker able to monitor for events globally.

Why? Because I can imagine that in my CQRS architecture I will have a process manager that will receive commands and execute them in sequence; while the commands will execute the process manager will also interact with the events raised by the Domain Models involved in the process.

I followed the article of Udi Dahan available here and I found a nice and brilliant solution of creating objects that act like Domain Events.

The final result is something like this:

public void SetState(OrderState orderState)
    state = orderState;
        new OrderStateChangedEvent(this.orderId, this.state));

The DomainEvents component is a global component that use an IoC container in order to “resolve” the list of subscribers to a specific event.

Next problem, notify by e-mail

When the Order Status changes, we should persist the change somewhere and we should also notify the environment, probably using a Message Broker.

We have multiple options here, I can just picture some of them, for example:

  • We can associate an Action<T> to our event, and raise the action that call an E-mail service
  • We can create a command handler in a different layer that will send an E-mail
  • We can create a command handler in a different layer that will send a Message to a Queue, this Queue will redirect the Message to an E-mail service

The first two options are easier and synchronous, while the third one would be a more enterprise solution.

The point is that we should decide who is responsible to send the e-mail and if the Domain Model should be aware of this requirement.

In my opinion, in our specific case, we have an explicit requirement, whatever there is a subscribed user, we should notify. Now, if we are smart we can say it should notify to a service and keep the Domain Model loosely coupled from the E-mail concept.

So we need to provide a mechanism to allow a User to register for an Update and verify that the User receives an E-mail.


I just need a way to provide an E-mail service, a temporary one, that I will implement later when I will be done with my domain. In this case Mocking is probably the best option here, and because my DomainEvents manager is providing methods using C# generics, I can easily fake any event handler that I want:

var handlerMock = 
      .Verify(x => x.Handle

Now, if you think for a second, the IHandles interface could be any contract:

  • OrderStateChangedEmailHandler
  • OrderStateChangedPersistHandler
  • OrderStateChangedBusHandler

Probably you will have an Infrastructure service that will provide a specific handler, a data layer that will provide another handler and so on. The business logic stays in the Domain Model and the event implementation is completely loosely coupled from the Domain. Every time the Domain raise an event, then the infrastructure will catch it and broadcast it to the appropriate handler(s).


The sample shown previously is a very simple object graph (1 object) that provides behaviors and data. It fits perfectly into BDD because the business logic is behavior driven thanks to the ubiquitous language and it does not involve any external dependency (services or persistence).

We can test the logic of our Domain in complete isolation without having the disadvantage of an anemic Domain that does not carry any “real” business value. We built a language that can be shared between the team and the analysts and we have tests that speak.

Probably an additional functionality could be to design the Commands in charge of capture the intent of the user and start to test the complete behavior. So that we will have an infrastructure where the system intercepts commands generated by the User and use these command to interact with the Domain Model.

Again, even for Domain Model the rule is the same than any other pattern (architectural and not). It does not require a Data Layer, it does not require a Service Bus and so on. The Domain Model should contain behaviors and data, then the external dependencies are external dependencies …

Now, if you will do your homeworks properly, you should be able to have some good fitness around your Domain Model like the following one:


BDD frameworks for NET

When I work in a project that implies Business Logic and Behaviors I usually prefer to write my unit tests using a Behavioral approach, because in this way I can easily projects my acceptance criteria into readable piece of code.

Right now I am already on Visual Studio 2013 and I am struggling a bit with the internal test runner UX, because it doesn’t really fit the behavioral frameworks I am used to work with.

So I decided to try out some behavioral frameworks with Visual Studio 2013. I have a simple piece of functionality that I want to test. When you create a new Order object, if the Order Id is not provided with the right format, the class Order will throw an ArgumentException.

If I want to translate this into a more readable BDD sentence, I would say:

Given that an Order should be created
When I create a new Order
Then the Order should be created only if the Order Id has a valid format
Otherwise I should get an error\

So let’s see now the different ways of writing this test …


XBehave is probably the first framework I tried for behavioral driven tests. The implementation is easy but in order to get it working properly you have to write your tests on top of xUnit test framework, and of course you have also to install the xUnit test runner plugin for Visual Studio.

In order to write a test, you need to provide the Given, When and Then implementations. Each step has a description and a delegate that contains the code to be tested. Finally, each method must be decorated with a [Scenario] attribute.

public void CreatingAnOrderWithValidData(string orderId, Order order)
        .When("creating a new Order",
                   () => order = Order.Create(orderId))            
        .Then("the Order should be created",
                   () => order.Should().NotBeNull());

In this specific case I am using the [Example] attribute to provide dynamic data to my test, so that I can test multiple scenarios in one shot.


The problem? For each step of my test, Visual Studio test runner identifies a unique test, which is not really true and quite unreadable because this is one method, one test but in Visual Studio I see a test row for each delegate passed to XBehave.


NSpec is another behavioral framework that allows you to write human readable tests with C#. The installation is easy, you just need to download the Nuget package, the only problem is the interaction with Visual Studio. In order to run the tests you need to call the test runner of NSpec, which is not integrated into the test runner of Visual Studio, so you need to read the test results on a console window, without the availability to interact with the failed tests.

In order to test your code you need to provide the Given,When and Then like with any other behavioral framework. The difference is that this framework is making an extensive use of magic strings and it assumes the developer will do the same.

void given_an_order_is_created_with_valid_data()
    before = () => order = Order.Create("xxx-11111-xxx");
    it["the order should be created"] = 
         () => order.should_not_be_null();

And this is the result you will get in Visual Studio Nuget package console (as you can see, not really intuitive and easy to manage):


Honestly the test syntax is quite nice and readable but I found annoying and silly that I have to run my tests over a console screen, come’n the interaction with Visual Studio UI is quite well structured and this framework should at least prints the output of the tests into the test runner window.


I came to StoryQ just few days ago, I was googling about “fluent behavioral framework”. The project is still on but it looks pretty inactive, so take it as is. There are few bugs and code constraints that force you to implement a very thigh code syntax, thigh to the StoryQ conventions.

The syntax is absolutely fluent and it’s very readable, compared to other behavioral frameworks, I guess this is the nearest to the developer style.

new StoryQ.Story("Create Order")
.InOrderTo("Create a valid Order")
.IWant("A valid Order object")

.WithScenario("Valid order id")


And the output is fully integrated into Visual Studio test runner, just include the previous code into a test method of your preferred unit test framework.


The output is exactly what we need, a clear BDD output style with a reference to each step status (succeed, failed, exception …)


BBDify is the lightest framework of the one I tried out and honestly is also the most readable and easy to implement. You can decide to use the Fluent API or the standard conventions. With both implementations you can easily build a dictionary of steps that can be recycled over and over.

In my case I have created a simple Story in BDDfy and represented the story using C# and no magic strings:

public void OrderIsCreatedWithValidId()
        Given(s => s.OrderIdIsAvailable())
        .When(s => s.CreateANewOrder())
        .Then(s => s.OrderShouldNotBeNull())
        .BDDfy("Create a valid order");

And the test output really fit into Visual Studio test runner, plus I can also retrieve in the test output my User Story description, so that my QAs can easily interact with the tests results:


I really like this layout style because I can already picture this layout into my TFS reports.

I hope you enjoyed!

TDD a WCF service, is it possible?

Right now I am working on a CQRS project, and I am using WCF as my web service technology. In this project I decided to challenge myself and make a full TDD project. The first big problem I found was to simulate a real web server, because I didn’t want to hit a production or QA environment to run my tests.
Second I didn’t want to write any integration test at all, so I had to figure out how to create an in-Process test to run my WCF methods.

Why in-process test? When you write a unit test, you should test a single functionality, and in order to make the test atomic, it should run in-process. It should not involve third party tiers like a database or IIS, otherwise the test won’t be in-process anymore, so it will became an Integration test.

The first idea I came out was to fake the behaviour of IIS, and in order to accomplish this I could easily work with a mock framework like Typemock and mock out the entire IIS infrastructure.

Is this what I really want? Not at all. I don’t want and I don’t need to fake the behaviour of IIS, I need an instance of it because my WCF services are using custom factories and custom behaviours and I need to be sure they are acting in the right way.

So I have created two different type of tests. The first one is pure Unit Test, where I verify the command behaviours:

   1: [TestMethod]

   2: public void AddUsersCommandHandler_ValidCommand_WillPersist()

   3: {

   4:     // arrange

   5:     AddUsersCommand expectedCommand = new AddUsersCommand { UsersStream = expectedStream };

   6:     // service with mocked unit of work

   7:     IServiceCommandHandler<AddUsersCommand> handler = new AddUsersCommandHandler(mockUnit.Object);


   9:     // act

  10:     handler.Handle(expectedCommand);


  12:     // assertions against the command behaviour

  13:     mockUnit

  14:         .Verify(x => x.BeginTransaction(), Times.Once());

  15:     mockUnit

  16:         .Verify(x => x.Save(It.IsAny<User>()));

  17:     mockUnit

  18:         .Verify(x => x.CommitTransaction(), Times.Once());

  19: }

The second one is the (in)famous integration test, where you call the WCF service and test the overall process. Unfortunately for the second step I couldn’t find anything really TDD so I had to figure out by myself a different solution.

IIS Express

Yesterday I spent some time googling around for a solution while I found a nice post from Scott Gu about IIS express. With IIS express we have an in-process IIS server that we can startup or shutdown at any time during the lifecycle of our tests. It provides almost all the functionalities provided by IIS and it also trigger the Application_Start event, something not very well handled by Cassini …

So, first of all I had to figure out how to bootstrap my unit tests to run over a different IIS than the one configured in the web.config.

Piece of cake, first of all I need something that allows me to bootstrap IIS express before my unit test harness starts:

   1: [ClassInitialize]

   2: public static void ClassInitialize(TestContext context)

   3: {

   4:     // create a process for IIS express

   5:     issProcess = new Thread(IssUtility.StartIisExpress) 

   6:                  { 

   7:                     IsBackground = true 

   8:                  };

   9:     // start it

  10:     issProcess.Start();

  11:     // create a new channel factory using the generated URL

  12:     factory = new ChannelFactory<IDomainWriteService>(

  13:        new BasicHttpBinding(), 

  14:        new EndpointAddress("http://localhost:5555/services/DomainWriteService.svc"));

  15: }

Then I need another utility to kill everything when my test harness is done:

   1: [ClassCleanup]

   2: public static void ClassCleanup()

   3: {

   4:     // close the WCF factory

   5:     factory.Close();

   6:     // shutdown IIS express

   7:     IssUtility.TearDownIis();

   8:     issProcess.Abort();

   9: }

At this point I can write any test in the following format:

   1: [TestMethod]

   2: public void ChannelFactory_ReceiveValidCommand_WillExecute()

   3: {

   4:     var expectedCommand = BuildAddUsersCommand();

   5:     service.AddUsers(expectedCommand);

   6: }

I found this technique very useful because we work with TFS on Azure so my Build environment cannot be polluted at all with any third party components or by installing the WCF service under test in the build machine.

In the same way I found very quick to bootstrap IIS express for my tests, honestly they are faster than running on my local IIS 8.

IIS Express utility class

Below is the code I use to initialize IIS express, feel free to use it in your tests and let me know if you come up with a better solution than this one.

   1: namespace xxx

   2: {

   3:     using System.Diagnostics;


   5:     public class IssUtility

   6:     {

   7:         private static Process iisProcess;


   9:         // Start IIS on port 5555

  10:         public static void StartIisExpress()

  11:         {

  12:             var startInfo = new ProcessStartInfo

  13:                 {

  14:                     WindowStyle = ProcessWindowStyle.Normal,

  15:                     ErrorDialog = true,

  16:                     LoadUserProfile = true,

  17:                     CreateNoWindow = false,

  18:                     UseShellExecute = false,

  19:                     Arguments =

  20:                         string.Format("/path:\"{0}\" /port:{1}",

  21:                                         @"your WCF dev path", 5555)

  22:                 };


  24:             var programfiles = string.IsNullOrEmpty(startInfo.EnvironmentVariables["programfiles"])

  25:                                     ? startInfo.EnvironmentVariables["programfiles(x86)"]

  26:                                     : startInfo.EnvironmentVariables["programfiles"];


  28:             startInfo.FileName = programfiles + "\\IIS Express\\iisexpress.exe";


  30:             try

  31:             {

  32:                 iisProcess = new Process {StartInfo = startInfo};


  34:                 iisProcess.Start();

  35:                 iisProcess.WaitForExit();

  36:             }

  37:             catch

  38:             {

  39:                 iisProcess.CloseMainWindow();

  40:                 iisProcess.Dispose();

  41:             }

  42:         }


  44:         // kill everything

  45:         public static void TearDownIis()

  46:         {

  47:             iisProcess.CloseMainWindow();

  48:             iisProcess.Dispose();

  49:         }

  50:     }

  51: }


Agile Architecture.

Last week I presented a webinar about Agile Architecture and I got an unexpected positive feedback from it. First it was unexpected because I didn’t expect to get lot of people interested in this particular topic. Second it was unexpected because I am still at the beginning of my teaching career and presenting webinars so I am not so good yet to keep the audience interested for 60 min.

Btw, considering the result of the webinar, I decided to post the video of the webinar (thanks to the guys of Typemock!) and a short introduction to Agile Architecture.

Agile Architecture webinar:

Update: slides available on SlideShare.

Agile architecture

What is Agile Architecture? It is a methodology that follows the Agile guidelines but differ from some aspect of its process.

At this web address: you can find probably the official website of this Agile methodology, even if you may find a lot of interesting discussions and articles here and there on the web, just google “Agile Architecture”.

Another interesting web site is where you can find tons of information about Agile Modeling and Agile Architecture. (If you watch the webinar I spoke about both of them).

Finally, if you want just to read a quick article and understand the overall process of Agile Architecture, I found this article of J.D. Meier very helpful: “How to design with Agile Architecture”.

TFS Template

I got various requests about the TFS and Dashboard templates I used during the webinar. I got them from the beta of Team Foundation Server 2011, available here. You need to customize the process to fit better Agile Architecture methodology. I am planning to prepare a custom template for TFS 2011 as soon as the SDK will be finalized.

Q/A from the webinar

Below is a short list of some of the most interesting Questions and Answers I got during the webinar. I am posting them here because during the webinar I wasn’t able to read them because I am using the MAC version of GoToWebinar.

Q: Acceptance Tests should have been written before the model.

Not really, if you adopt the strict TDD all the acceptance tests should be written before, but when you envision the architecture, it is too early to write acceptance
tests. When you start the iteration and you have your requirements defined, you may start to model against the acceptance criteria for that iteration. But remember
that the modeling part should be light enough to provide value for the next step.

Q: the functions of the architect are clear, but it is not clear how these functions are intended to fit into the Sprints.

The sprint is composed by three parts, modeling, brainstorm and coding. The architect will perfectly fit into each of this phase. I think I have explained this
concept during the webinar, but just to be sure. During modeling and brainstorm the architect should help with his knowledge and collaborate in the modeling, during
the coding he should be an active coder too and contribute to the technical decisions providing knowledge and expertise.

Q: Can you elaborate on what you mean with the “design phase”?

Ok, during the first iteration, the envision, there is a light design phase. You should design some scratches of your envision, representing the architecture and the UI, but you should not invest too much time.
Design phase while modeling means adopting UML to design your models.

Q: How does your “Iter: 0” relate to the PO, backlog and sprint planning?

Ah ah, interesting. The envision or iteration 0 is tricky to fit into SCRUM. Take the classic meter to measure an iteration, like 1 or 2 weeks. Inside this timeframe you should have enough space and time to prepare the necessary analysis and mocks required by next steps. So you may consider iter 0 like a beginning sprint.

Q: Couldn’t the use-case diagram be enough for the modelling phase? I’m interested in hearing your reasoning because I’m currently in this situation in my current project. What level of detail is enough when it comes to architecture that lets developers use their brain and problem solving power?

No, the use case is not enough because it may incur into personal interpretation. With the use case and the acceptance you and your team are ready for the modeling phase, where you create the architectural style for that feature. The modeling should be enough to represent the current feature and it should not be implemented, the implementation occurs in the next phase where you apply TDD against the model discussed in the previous part. It is hard to keep the model the blueprint of the code and often it doesn’t provide value. It is important that the model represents what you are delivering.

Q: Does the Process workflow you describe impact the philosophy of embracing change? How can we perform radical change when we get a bigger up-front model?

No, it doesn’t because Agile Architecture pretends the flexibility into your model. Model just enough to represents the feature and remember that you can always come back and re-model and re-factor. Embracing Agile Architecture will force you to have a dynamic more agnostic and flexible model than using a classic architecture approach.
Why would you get a radical change request with a radical model upfront? Of you adopt Agile you should structure these changes into small iterations.

The envision phase is the most critical, you or the architect need to understand what the stakeholder wants from your team. If you get that, you are in a good starting position.
The big mistake is to take too much for the envision, which is not the modeling phase. Mocking out your application doesn’t mean to model everything, so the envision should take few days, at most one week. If it takes more you may have some smells in your team: lack of requirements, lack of business knowledge, lack of technical knowledge.
Remember that every iteration has a modeling phase and a brainstorm phase, so you may move back to the envision and adapt it to the new requirements.

TypeMock tutorial #03. Control behaviors.

Note for purists: In this tutorial I am showing you a simplified example of a Unit of Work and a Repository, please do not care about the complexity or simplicity of these objects but look at the TypeMock implementations.

We are now at the third post of this series and I found out that there are a lot of readers interested in learning TypeMock, which means that series will have to continue!

Last time, we have created some object’s mocks using TypeMock but they were simple Value Objects with nothing or very few business logic in it. This time I want to show you how you can control the behaviors of a mock so that you do not have to control or fake the entire object if you are testing a single method.

Testing a IUnitOfWork

I do not know if you have already created a data layer in your career of software developer; if you did not, you can have a look at one of my tutorials or books about layering an application.

First of all we have a Unit of Work, which allows us to “Save”, “Update” or “Delete” the object we are passing it using a generic signature. The contract for a Unit of Work is represented by the following image:


As you can see we have a simple interface with three methods and we still do not have an implementation for it but we have some expectations that we would like to pre-test using a mock in order to be sure that the next step will be properly handled by TypeMock.

The pre-requisite is that every entity in our domain has some properties inherited by a base class DomainObject; these properties can tell us the ID of the entity, if the entity is new, modified or deleted.

The following object represents the base class for a domain entity.


The 3 properties are of type boolean while the UniqueId is of type Guid, so by default we will have a Guid.Empty value and after we mark dirty or updated the object we should have them populated.






Test the interface

If we test the interface we can start by writing three different expectations like the three following snippets:

Mark a new entity
  1. [Test]
  2. [Category(“DataLayer”)]
  3. public void CanMarkANewEntityToNewAndChangeItsId()
  4. {
  5.     Person person = Isolate.Fake.Instance<Person>();
  6.     IUnitOfWork uow = Isolate.Fake.Instance<IUnitOfWork>();
  7.     uow.MarkNew(person);
  8.     Assert.That(person, Has.Property(“UniqueId”).Not.EqualTo(Guid.Empty));
  9.     Assert.That(person, Has.Property(“IsNew”).True);
  10. }

And as soon as we run this test it simply fails because of course TypeMock is not able to properly mock the method MarkNew as we did not instruct it on how to do it …

The solution in this case is pretty straightforward, before invoking the MarkNew<T> method we need to teach to TypeMock what is our expectation for this method when we add a Person object to it.

  1. Isolate.WhenCalled(() =>
  2.     uow.MarkNew(person))
  3.     .DoInstead(callContext =>
  4.                    {
  5.                        var p = callContext.Parameters[0] as Person;
  6.                        p.UniqueId = Guid.NewGuid();
  7.                        p.IsNew = true;
  8.                        return p;
  9.                    });
  10. var expectedPerson = uow.MarkNew(person);

In this case we have informed TypeMock that when we will call the method MarkNew<T> passing as a generic paramenter the Person object, it will have to modify the person object and return it with a new ID and the IsNew property populated.

Another way to do that is to use the WillReturn method of TypeMock that can be used, like in this case when we have functions and not void methods.

  1. person.UniqueId = Guid.NewGuid();
  2. person.IsNew = true;
  3. Isolate.WhenCalled(() => uow.MarkNew<Person>(person)).WillReturn(person);
  4. var expectedPerson = uow.MarkNew(person);

In the same way we can test that the method may also return an unexpected exception, so we can inform TypeMock to force the mock interface to throw an exception.

This section of type mock is called Controlling method behaviors and you can find a detailed documentation about it at this address:

controlling methods

In the next tutorial we will see how to customize a chain of mockup object and faking the methods so that the IUnitOfWork will be used as a dependency for a Repository class.

If you want you can also download the code of every tutorial at this address on Codeplex:

Winking smile

Encrypted string of the week: IHcKGzESRVs=
using Blowfish CBC 64bit

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 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.


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>();
  3. public IEnumerable<Address> Addresses
  4. {
  5.     get { return this.addresses; }
  6. }
  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. }
  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. }


Constructor of an Address obj
  1. public Address(Person person)
  2. {
  3.     Person = person;
  4. }
  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:


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. }
  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. }
  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 …


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);
  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!


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

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.