BDD with Specflow

This post will be part of a series about developing my sample application (Sell and Buy).

Starting from very initial documentation describing Ubiquitous Language and User Stories.

As described in Wikipedia, BDD encourages collaboration between team members and business stakeholders.  It describes a cycle of interactions with well-defined outputs, resulting in the delivery of working, tested software that matters. Behavior-driven developers use their native language in combination with the ubiquitous language of domain driven design to describe the purpose and benefit of their code.

Recently I’ve played with SpecFlow, and found it very appealing in defining behaviors specially end-to-end tests. So I started my solution by creating a SpecFlow project taking the first user story and apply it then start to build the walking skeleton.

It is not very much walking skeleton, as I had to invest a little more time designing the infrastructure and basic layers of the applications.

Story 1.1: List recent ads

As a buyer, I want to find recent ads, so that I can find something interesting.

This very first user story states that when a user first open homepage, he should see a list of recent ads. The following is the implementation using SpecFlow:

A feature in SpecFlow is mapped to a user story using the same syntax of user story.

A Background describes the givens, it is very beneficial here because in this user story, we assume that there are already definitions in the system. We assume that there is a customer (seller), a category (Books), some available conditions for the ad type, some items definitions, and finally a list of ads published.

Each feature in SpecFlow is mapped to Steps definition file which is a class bound to the feature with methods bound to elements in the feature to execute it.

for example “Given the following customers” will be mapped to a method  with Table as parameter filled with customers in the feature.

        [Given(@"the follwing customers")]
        public void GivenTheFollwingCustomers(Table table)
        {
            var customers = new List<Customer>();
            foreach (var tableRow in table.Rows)
            {
                var customer = new Customer
                                   {
                                       FirstName = tableRow["First Name"],
                                       LastName = tableRow["Last Name"],
                                       Email = tableRow["Email"]
                                   };
                customers.Add(customer);
            }

            GetCustomerRepository().Add(customers);
            GetCustomerRepository().UnitOfWork.Commit();
        }

The first scenario starts with the condition “When I enter homepage” would be mapped to:

        [When(@"I enter home page")]
        public void WhenIEnterHomePage()
        {
            var AdService = GetAdService();

            var controller = new HomeController(AdService);

            _actionResult = controller.Index(null, null);
        }

This code instantiates a new ASP.Net MVC HomeController passing it AdService instance and calling Index method which will return ActionResult.

Then comes the expectation “Then the home page shows ads …” which is mapped to:

        [Then(@"the home page shows ads")]
        public void ThenTheHomePageShowsAds(Table table)
        {
            var adsViewModel = _actionResult.Model();

            foreach (TableRow row in table.Rows)
            {
                CustomAssert.Any(adsViewModel.PageItems,
                                 a =>
                                 a.Item.Name == row["Title"] &&
                                 a.Description == row["Description"] &&
                                 a.Price == Decimal.Parse(row["Price"])&&
                                 a.Customer.FirstName == row["Customer First Name"]&&
                                 a.Customer.LastName == row["Customer Last Name"]);
            }

            Assert.AreEqual(table.Rows.Count(), adsViewModel.PageItems.Count(), "The list contains other ads too");
        }

This code gets the view model from the actionresult and assert that it includes expected fields.

This very first user story started to give us an idea of end to end test, at this stage we are in the phase of creating the walking skeleton which will include infrastructure layers and domain entities, persistence, services … In later posts we will discuss the rest of implementation.

Logging (Service locator, DI, or AOP)

One of the most common cross cutting infrastructure aspect of enterprise applications is Logging, It can be categorized to two different types:

  • Tracing: Usually used to debug application by tracing method calls and sequence of execution.
  • Logging: When you want to deliberately log some informative message to the log.
The first type of logging always cluttering application code and introduce a redundant dependency upon logging interface whether this interface is consumed using static Factory, Service Locator, or Dependency Injection Container).
Using dependency injection in constructor will clutter the constructors of almost all application classes where each one will add a constructor parameter for the logger interface.
Using setter injection or service locator or static factory will resolve this issue but we still have logging code in each method beside the problem of hiding dependency.
The best solution to tracing is to use Aspect Oriented Programming to inject tracing code to all required method calls, there are many types of AOP tools you can use one of these tools to inject tracing code in your project.
A sample implementation using Unity is provided in this sample.
As the project already use Unity for dependency injection, I used interception to intercept method calls:
    public class TraceCallHandler : ICallHandler
    {
        #region Fields

        private readonly IUnityContainer _container;

        #endregion

        #region Properties

        public int Order { get; set; }

        #endregion

        #region Constructors

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="container"></param>
        public TraceCallHandler(IUnityContainer container)
        {
            _container = container;
        }

        #endregion

        #region Methods

        /// <summary>
        /// Invoke method
        /// </summary>
        ///input">method invacation info
        ///getNext">next handler delegate
        /// <returns></returns>
        public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        {
            var className = input.MethodBase.DeclaringType.Name;
            var methodName = input.MethodBase.Name;
            var arguments = GetCommaSeparatedArgumentList(input.Arguments);

            var preMethodMessage =
                string.Format("{0}.{1}({2})", className, methodName, arguments);
            ServiceLocator.Current.GetInstance<ILogger>().
                Debug(className, preMethodMessage);

            var methodReturn = getNext()(input, getNext);

            if (methodReturn.Exception != null)
                _container.Resolve().Debug(className,
                  String.Format("Exception intercepted: {0}",
                                       methodReturn.Exception));
            else
            {
                var postMethodMessage = string.Format("{0}.{1}() -> {2}",
                                                      className, methodName,
                                                      methodReturn.ReturnValue);
                _container.Resolve().Debug(className, postMethodMessage);
            }

            return methodReturn;
        }
This code creates a call handler interceptor to intercept method calls, it print call with its parameter types, values, returned value, and exception if happened.
    public class AnyMatchingRule : IMatchingRule
    {
        public bool Matches(MethodBase member)
        {
            return true;
        }
    }
A matching rule is to match the criteria of selecting methods to inject in.
Finally you need to configure Unity to register these extensions and inject it to the given interfaces:
  xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <sectionExtension type="...InterceptionConfigurationExtension, ...Interception.Configuration" />
    <typeAliases>
      <typeAlias alias="AnyMatchingRule" type="Extensions.Unity.AnyMatchingRule"/>
      <typeAlias alias="TraceCallHandler" type="Extensions.Unity.TraceCallHandler"/>

      <typeAlias alias="ILogger" type="Logging.ILogger, Infrastructure.Core"/>
      <typeAlias alias="Log4NetLogger" type="Logging.Log4NetLogger, Infrastructure.Core"/>

      <typeAlias alias="IMyService" type="IMyService"/>
      <typeAlias alias="MyService" type="MyService"/>
      </typeAliases>

    <container>
      <extension type="Interception" />

      <register name="Any"
         type="IMatchingRule"
           mapTo="AnyMatchingRule" />
      <register
         type="ICallHandler"
           mapTo="TraceCallHandler" />

      <register
         type="ILogger"
           mapTo="Log4NetLogger" />

      <register
          type="IMyService"
          mapTo="MyService" >
        <interceptor type="InterfaceInterceptor" />
        <policyInjection />
      </register>

      <interception>
        <policy name="All">
          <matchingRule name="Any" />
          <callHandler name="TraceCallHandler" type="TraceCallHandler" />
        </policy>
      </interception>
    </container>
  </unity>
Now you can get rid of all calls of logger in all the methods.
About logging extra or custom information you will still need to get the logger, either using DI or Service Locator.

Entities and Value Objects

One of the building blocks of a Domain Driven Design application are entities and value objects.

Entity is an object with identity, it is defined by its identity and continuity not its attributes, for example a person is an entity with identity (maybe it is social security number, maybe a user id, maybe Guid) but this person remains the same even after changing his address or even his name. two instances of person objects with the same identity are the same even if they are not the same object in memory, even if they have different attributes (Properties and Fields) thus it is a mutable type, you can change its attributes and it remains the same entitiy.

Value Object on the other hand is an object that contains attributes with no conceptual identity, two value objects with the same attributes are the same. thus it is immutable type, when you change any attribute of value object it becomes a different value object. an example of value object is address (unless your application domain states that address is a key information with identity like shipping applications), the address is a value object attached to the person, you can not identify address on its own, you just can fetch a person entity and get the address.

When developing a DDD application in .net usually I create a Layer Super Type for entities and value objects as follows:

EntityBase: Each entity should have Identity, this identity could be an int (auto number), a Guid, a string, custom identity object, or any type. this identity should be the base of object hash code, equality, and comparing operators. the following base class handles these aspects:

    public abstract class EntityBase<TEntity, TID> :
        IEquatable<EntityBase<TEntity, TID>>
        where TEntity : EntityBase<TEntity, TID>
    {
        #region Identity

        public virtual TID ID { get; protected set; }

        #endregion

        #region Overrides

        /// <summary>
        /// Indicates whether the current object
        /// is equal to another object of the same type.
        /// </summary>
        /// <returns>
        /// true if the current object is equal
        /// to the <paramref name="other"/> parameter;
        /// otherwise, false.
        /// </returns>
        /// <param name="other">An object to compare with this object.</param>
        public bool Equals(EntityBase<TEntity, TID> other)
        {
            if (other == null)
                return false;

            // Handle the case of comparing two NEW objects
            var otherIsTransient = Equals(other.ID, default(TID));
            var currentIsTransient = Equals(ID, default(TID));

            if (otherIsTransient && currentIsTransient)
                return ReferenceEquals(other, this);

            return other.ID.Equals(ID);
        }

        /// <summary>
        /// Equality
        /// </summary>
        public override bool Equals(object obj)
        {
            var other = obj as TEntity;

            return Equals(other);
        }

        /// <summary>
        /// Get hash code
        /// </summary>
        public override int GetHashCode()
        {
            var thisIsTransient = Equals(ID, default(TID));

            // When this instance is transient, we use the base GetHashCode()
            return thisIsTransient ? base.GetHashCode() : ID.GetHashCode();
        }

        /// <summary>
        /// Equal operator
        /// </summary>
        public static bool operator ==
            (EntityBase<TEntity, TID> x, EntityBase<TEntity, TID> y)
        {
            return Equals(x, y);
        }

        /// <summary>
        /// Not equal operator
        /// </summary>
        public static bool operator !=
            (EntityBase<TEntity, TID> x, EntityBase<TEntity, TID> y)
        {
            return !(x == y);
        }

        #endregion
    }

The entity base has two generic parameters, one for the type of entity TEntity, and the other for identity type TID, it implements IEquatable .net interface.

ID field is defined in line 7 using the TID type.

Implementation of strongly typed IEquatable Equals method and Object override Equals methods are provided to handle equality of two entities given and check their transient state. transient means that the entity has been created without setting the ID yet, thus the ID have a default value based on type (if reference type will be null, if primitive type will hold the default value), of course there should not be an entity defined with an id of null or default value. if both entities are transient then we have to check if they point to the same memory address thus they are the same object in terms of .net, otherwise we shall compare the identities.

The equals and not equals operators are also implemented and the GetHashCode also should return the identity’s hash code.

ValueObjectBase: Value object have no Identity, object hash code should represent the hash code of all it’s attributes, equality, and comparing operators should compare all and each field in the object:

    public class ValueObjectBase<TValueObject> :
        IEquatable<TValueObject>
        where TValueObject : ValueObjectBase<TValueObject>
    {
        #region Overrides

        /// <summary>
        /// Indicates whether the current object
        /// is equal to another object of the same type.
        /// </summary>
        /// <returns>
        /// true if the current object is equal
        /// to the <paramref name="other"/> parameter; otherwise, false.
        /// </returns>
        /// <param name="other">An object to compare with this object.</param>
        public bool Equals(TValueObject other)
        {
            if (other == null)
                return false;

            // Compare all public properties
            var publicProperties = GetType().GetProperties();

            if (publicProperties != null && publicProperties.Any())
                return publicProperties
                    .All(item => item.GetValue(this, null)
                    .Equals(item.GetValue(other, null)));

            return true;
        }

        /// <summary>
        /// Equality
        /// </summary>
        public override bool Equals(object obj)
        {
            // If both are null, or both are same instance, return true
            if (ReferenceEquals(obj, this))
                return true;

            if (obj == null)
                return false;

            var item = obj as ValueObjectBase<TValueObject>;

            if (item == null)
                return false;

            return Equals((TValueObject) item);
        }

        /// <summary>
        /// Get hash code
        /// </summary>
        public override int GetHashCode()
        {
            var hashCode = 31;
            var changeMultiplier = false;
            const int index = 1;

            // Compare all public properties
            var publicProperties = GetType().GetProperties();

            if (publicProperties != null && publicProperties.Any())
            {
                foreach (var value in publicProperties
                    .Select(item => item.GetValue(this, null)))
                {
                    if (value != null)
                    {
                        hashCode = hashCode * ((changeMultiplier) ? 59 : 114)
                            + value.GetHashCode();
                        changeMultiplier = !changeMultiplier;
                    }
                    else
                        hashCode = hashCode ^ (index * 13); // Support order
                }
            }

            return hashCode;
        }

        /// <summary>
        /// Equal operator
        /// </summary>
        public static bool operator ==
            (ValueObjectBase<TValueObject> x, ValueObjectBase<TValueObject> y)
        {
            return Equals(x, y);
        }

        /// <summary>
        /// Not equal operator
        /// </summary>
        public static bool operator !=
            (ValueObjectBase<TValueObject> x, ValueObjectBase<TValueObject> y)
        {
            return !(x == y);
        }

        #endregion
    }

This implementation is taken from Cesar de la Torre which uses reflection to compare all the fields of the value object.

The Ubiquitous Language

One of the main concepts of Domain Driven Design is the Ubiquitous Language.

Briefly Ubiquitous Language is the common language of communication between project stakeholders (mostly developers and business users). one of the major issues of software projects is communication between customer and development teams, there have to be a common language they stick to, to avoid misconception and misunderstanding of terms.

Developers usually use technical terms and jargon terms that business users don’t understand, also business users use business terms that developers don’t understand, a common language set to resolve these misunderstandings and close the gap between developer’s language, even coding language and business requirements and business users’ language.

It becomes a negotiable language between developers and business users and between team members and other stakeholders.

In my DDD Sample Project (SellAndBuy), the first step in developing the application is to elaborate briefly on the basic ubiquitous language terms used in the application, you can check it under documentation.

A couple of simple user stories implemented so we can start elaborating the design to meet these requirements in the following posts.

Revolution.Restart();

Another revolutionary day in Egypt and Tahrir Square.
Viva Egypt :)

 

Applying Domain Driven Design, BDD, and TDD

Being a big fan of Domain Driven Design and applying Domain Model Architecture Pattern, and recently advocating agile techniques like Behavior Driven Development and Test Driven Development, I started a new open source project hosted at CodePlex for applying these design techniques.

The project is about a fictional advertising portal like eBay, for more information about the project visit its web page SellAndBuy.

New blog

I decided to start a new blog, I used to have account in Blogger with a couple of posts every long while, So I decided to create a new blog, after studying blogging platforms I decided to use WordPress.