Extract and Override pattern for Unit Testing

by Nimesh 17. July 2011 19:58

I was relatively new to Unit Testing before couple of years but have horned my skills in unit testing since then. Before that, I (and my team members) always complained ad-hoc nature of the business and time constraint factor for not writing unit tests. Though I agree it was the factor most of the time, but it also came down to us not being strict in writing tests and getting better code coverage. Unless the code hasn't got proper test coverage, code is always suspect to errors during future changes.

Recently, working with 3rd party components, came across few scenario's which was comparatively tough and time consuming operation to test. When doing unit testing, one always comes to a point where there this “kind of hard” part to test since the part depends on something you might not have control over or depends on the functionality of the dependency to complete.

In self written code, I usually prefer laying down strict contract for the components via Interfaces, pass it in the constructor (constructor injection) and mock using Mocking framework (I prefer Moq) and hence, no big issue while writing unit tests.

But consider scenarios when you don’t have access to component or there will not be a setter for property on the object (3rd party component object) for some reason (probably security).

In above scenario, Extract and Override pattern for Unit Testing comes handy.

I will try explaining it using my favourite HybridCar class example. I would recommend you have a look at Dependency Injection explained article.

public interface IFuel
{
    string UnitOfMeasurement { get; set; }  //litres, gallon etc..
    decimal PricePerUnit { get; set; }
    string CalculateMileage();
}

public class Petrol : IFuel
{
    private string _unitOfMeasurement;
    private decimal _pricePerUnit;
 
    #region IFuel Members
 
    public string UnitOfMeasurement
    {
        get { return "Litre"; }
        set { _unitOfMeasurement = value; }
    }
     
    public decimal PricePerUnit
    {
        get { return 1.30M; }
        set { _pricePerUnit = value; }
    }
     
    public string CalculateMileage()
    {
        return "While driving in city, using Petrol as a Fuel gives 10km mileage";
    }
 
    #endregion 
}

public class HybridCar
{
	private StartValidator _validator
    private IFuel _fuel; 
    public HybridCar(IFuel fuel)
    {
        _fuel = fuel;
    } 
    public string Drive()
    {
        return _fuel.CalculateMileage();
    }

	public bool Start()
	{
		if(_validator.IsValid())
			return true;
		return false;
	}
}

Consider, StartValidator is the class which is not mockable or it's a legacy code where performing refactoring and extracting interface would be a big job. For us to test Start method, we have a dependency that calls and checks if the condition is valid for the HybridCar to start, this basically makes it pretty hard to test, unless we refactor our code and user interface IStartValidator, pass it in the constructor and mock StartValidator using moq or hand write the stub class for it. But as I mentioned before, consider we don't have access to the StartValidator class.

This sort of scenarios can be one of the reason where people don't write test for the code and the code coverage falls over. But there is a way to test and it is quite simple. The way to do it is actually extracting the dependency and test the Valid functionality. Since with us, we don't really care about the implementation detail for IsValid, as we want to test the Start functionality to see if it's valid to start. Let's see how to do it.

public class HybridCar
{
	private StartValidator _validator
    private IFuel _fuel; 
    public HybridCar(IFuel fuel)
    {
        _fuel = fuel;
    } 
    public string Drive()
    {
        return _fuel.CalculateMileage();
    }

	public bool Start()
	{
		if(IsValid())
			return true;
		return false;
	}
	
	protected virtual bool IsValid()
	{
		return _validator.IsValid();
	}
}

We added a virtual method called IsValid so that we can override it when we create a stub for it. Now for our stub, we simply override the IsValid method so that it always returns true (or change it based on your test cases).

public class HybridCarStub : HybridCar
{
	public bool Valid = true;
	protected override bool IsValid()
	{
		return true;
	}
}

And finally in our unit test, we can write something like this

[Test]
public void Start_IsValid_ReturnsTrue()
{
		//Arrange-------
		HybridCar car = new HybridCarStub();
		car.Valid = true;
		
		//Act-----------
		bool result = car.Start();
		
		//Assert--------
		Assert.IsTrue(result);		
}

[Test]
public void Start_IsNotValid_ReturnsFalse()
{
		//Arrange-------
		HybridCar car = new HybridCarStub();
		car.Valid = false;
		
		//Act-----------
		bool result = car.Start();
		
		//Assert--------
		Assert.IsFalse(result);	
}

Usually while writing tests, I tend to follow a AAA pattern (Arrange-Act-Assert), which helps in seperating the logical content of tests. It also helps someone else to go through the test code quickly. There are definitely better ways to lay your architecture to suit testing requirements but in certain scenarios, extract and override pattern for unit testing out ways the amount of effort required to refactor the code to make it unit testable.

Including Additional Files using MSBuild

by Nimesh 19. June 2011 07:27

Many times you will need to include files using MSBuild that are not part of the project, but need to be published. Recently, I was asked to improve our deployment scripts/process to take into account configuration files for different environment [Lab/Stage/Offline-Production/Production] with same build package/content.

In our present deployment process, we have to run the deployment process 4 different times [deploy Stage/deploy Lab, etc..] to get the configuration carried across the particular environment. What I was intending to do was to have one deployment command which generates deployment package suitable for all the environments. Intention was to get the deployment done automatically with batch file and using MSBuild and MSDeploy. After getting the configuration files for different environment under TRANSFORM_CONFIGS folder as shown below, my next step was to include this folder in my build. The deployment package structure shown below is located at C:\Temp\DeployPackage. Steps required to generate configuration files for different environment is a blog post in waiting..... stay tuned!!!

deploy_structure1

More...

Tags:

.Net | continuous-integration | msbuild | msdeploy

ASP.Net Mobile Device Detection and Redirection Module

by Nimesh 22. May 2011 07:44

In my perspective, there are two parts for mobile device detection, one a top level module that resides at the entry point of our desktop site and other being the layer of detection that is far more granular that sits at the entry point of mobile site.

The responsibility of module that resides at the entry level of our desktop site is to detect whether the request is coming from a mobile device and appropriately redirect to the mobile site. Whereas, the responsibility of the detection layer that resides inside the mobile site is far more granular and it should detect the manufacturer, model, version number of OS, etc to redirect them to appropriate view based on those factors.

In this article I will concentrate on the ASP.Net module that resides on our desktop site which detects the device based on User Agent and redirects to appropriate mobile site.

I have an interface whose primary responsibility is to detect the device based on the UserAgent of the browser.

 

    /// <summary>
    /// Responsible for detecting the device making the request.
    /// Note: Can be extended for mobile project to make detailed detection
    /// of the device using wurfl file. As of now, the detection is based
    /// on the useragent supplied in the request.
    /// </summary>
    public interface IDeviceDetection
    {
        /// <summary>
        /// Should be logically supplied from the configuratin file but will
        /// make it return true as of now.
        /// This logic is enhanced, so when the request has got querystring
        /// nomobile=true, set a cookie and set the RedirectEnabled = false;
        /// Read the cookie first and if it's set, disable the redirection
        /// </summary>
        bool RedirectEnabled { get; set; }
 
        /// <summary>
        /// Primary method which detects the device based on the useragent
        /// passed in the request. Can be extended to use the wurfl file later on
        /// </summary>
        /// <param name="context">Current HttpContext object</param>
        /// <returns>true if the request came from mobile device for non-mobile web page; else false</returns>
        bool ShouldRequestRedirect(HttpContext context);
 
        /// <summary>
        /// When module gets the request back from mobile site to view full site,
        /// it comes with a qrystring "noredirect=true". After we get that qrystring,
        /// set a cookie so that the future requests doesn't get redirected to mobile sites.
        /// </summary>
        /// <param name="context">Current context</param>
        void SetRedirectionFlag(HttpContext context);
 
        /// <summary>
        /// Not all the request for the resources should be intercepted by this
        /// module, only handlers should be intercepted and processed
        /// </summary>
        /// <param name="context">Current HttpContext object</param>
        /// <returns>true if the request if for a asp.net handler</returns>
        bool IsRequestForHandler(HttpContext context);
    }

More...

Tags:

.Net | ASP.Net Architecture | Mobile

Attributes of Controllers and Action Methods in ASP.Net MVC

by Nimesh 16. April 2011 18:39

I started to learn MVC by my own during my free hours. Every time I get back, I find few terms confusing and tough to remember their role. There are couple of MVC books I am reading at the moment and both are impressive in their own right. One is Programming Microsoft ASP.Net MVC by our own Dino Esposito and the other is ASP.Net MVC in action by few authors.

I am noting down this feature and area of MVC for my own future reference as well as keeping an eye on knowledge sharing too.

There are 3 categories of attributes that affect a controller class and its methods: filters, invocation attributes, and action selectors

More...

Tags:

.Net | MVC

Extending Authorize Attribute in ASP.Net MVC

by Nimesh 11. April 2011 18:38

If you have previously used Authorize attribute for any action method in MVC, you should have noticed that MVC doesn’t distinguish between users who are not logged in and logged-in users that do not have the rights to invoke a given action method. In both cases, the attempt to call the action method fails and the user is redirected to the login page.

You might or might not like this behaviour. Certainly, I don’t want any confusion for my users. I don’t want a logged in user to be again redirected to the login page and ask him to login. This behaviour is default asp.net MVC behaviour and I want to override the behaviour by implementing enhanced attribute class of my own.

You use the Authorize attribute when you want to make sure that only authorized users can gain access to a particular method or to any action methods in a given controller. Here’s an example:

[Authorize]
public ActionResult About()
{
    //implementation....
}

More...

Tags:

.Net | MVC

Back from Holidays

by Nimesh 18. February 2011 01:33

Well, we’re back from the holidays spanning right from mid December till end of January. I hope you all enjoyed it as much as we did. It’s been almost 4 weeks since we are back, but still haven’t been able to clear backlogs of work.

Myself and my wife went to India after almost a gap of two and half years. On the way to India, took transit to KLM and on the way back from India, went to Phuket. Had a great time in India too, just a bit more social than my liking, but it all went good.

Back to business, this year I wish to learn/master more technologies and want to specifically concentrate on MVC, mobile development.

Tags:

Personal

Service Locator with Dependency Injection Container

by Nimesh 11. December 2010 05:54

In my previous post, I explained the use of Unity Container to inject dependency at runtime. I recommend to read previous article first to get clear picture of the reason we want to implement Service Locator kind of pattern with any Dependency Injection Container.

If you look at the previous article, we have used the following code to register a type and then resolve the component inside a container.

using (IUnityContainer container = new UnityContainer())
{
    container.RegisterType<IFuel, Petrol>();
    IVehicle car = container.Resolve<HybridCar>();
    lblOutput.Text = car.Drive();
}

More...

Tags: , , ,

.Net | Dependency Injection | Design Patterns | Unity

Dependency Injection using Unity Container

by Nimesh 5. December 2010 03:14

In previous post, I explained what is Dependency Injection and how it can be used to develop loosely coupled applications. In this post, we will use Microsoft Unity 2.0 as the dependency injection container. There are various other dependency injection containers that can be used with .Net as listed by scott hanselman. We will use Unity as our dependency injection container but the overall purpose of it remains the same in whichever technology you use.

In our previous example, we used an example of Petrol as a fuel in our Hybrid car. We will extend on the same example, so if you haven’t read it, I would suggest reading my previous article first.

More...

Tags: , ,

.Net | Design Patterns | Unity

Dependency Injection Pattern Explained

by Nimesh 26. November 2010 06:45

Why?

Dependency Injection pattern, which is also referred as Inversion of Control facilitates the implementation of loosely coupled, testable components in an application. In order to understand loosely coupled component of a system and what benefits it brings to the overall architecture, we will use a simple example. In this example, I’m writing a component that drives the car using the Fuel (petrol/diesel/gas/solar) supplied.

public interface IFuel
{
    string UnitOfMeasurement { get; set; }  //litres, gallon etc..
    decimal PricePerUnit { get; set; }
    string CalculateMileage();
}

More...

Tags: , ,

.Net | Dependency Injection | Design Patterns

Common Terminologies used in WCF

by Nimesh 22. November 2010 04:18

When I initially read about WCF before couple of years, I was very much confused with the terminologies used. WCF comes with tones of configuration options and if you are not spontaneous with the terminologies/taxonomy of WCF, it will become extremely tedious to configure the WCF service/client. I would like to summarize few introductory terms which are commonly used in WCF services which may help you understand WCF better.

wcf_communication

More...

Tags: , ,

.Net | WCF | Distributed Technology

HttpPipeline in ASP.Net Request Processing

by Nimesh 9. November 2010 13:19

As stressed many times, it's highly essential for .Net Developers to understand the request processing architecture for any resource on the web server to develop highly optimized application. In addition to that, understanding the pipeline will assist you in troubleshooting as well. In past couple of years, I had to switch my focus between various applications (web, windows, services, etc...) and the first thing I do when coming back to web application, was to revise ASP.Net Request architecture. I thought of laying down that understanding of mine as a blog (to assist me as I keep forgetting if I am not into web development for few months).

In previous article, we saw what role IIS plays in ASP.Net request processing. One of the intermediate step (step 5) in the request processing was "The ASP.Net ISAPI will load the ASP.Net Runtime and executes the request and loads the response object". This article will focus on that particular step when the request lands into ASP.Net Pipeline. More...

Tags: , ,

ASP.Net Architecture | IIS

ASP.Net & IIS Request Response Architecture

by Nimesh 5. November 2010 23:06

A while back, I had few issues getting one of the IIS 6 targeted website to work on IIS 7. At that moment, I rated myself as a newbie as far as IIS terminologies were concerned. When I opened Advanced Settings on my website's Application Pool, I saw part of it something as shown in below image. Two properties caught my attention straight away : Managed Pipeline Mode - Integrated and Queue Length - 1000 as shown in below image.

adv_settings

Managed Pipeline Mode has two options - Integrated, Classic. Next step, no surprise, was to Google the differences. I got fair bit of understanding reading few scattered posts and articles, and that governed me to write this blog which will highlight the ROLE OF IIS in ASP.Net Request/Response Architecture. More...

Tags: , ,

ASP.Net Architecture | IIS

Getting Subdomain from an URL in .Net

by Nimesh 1. November 2010 23:13

Recently, I was writing a logic which required stripping out all the bits and pieces from an url.

For instance,

Request Host URL : a.b.c.domain.com.au  has to be separated into

  • subdomain = a.b.c
  • domain = domain
  • com = com
  • countryextension = au

Note: This example was to suit my scenario and I may/may-not have covered all the scenarios possible for the URL combinations. You can definitely go ahead and modify the regex to suit your need.

Obviously, the first thing that comes to our mind is writing a regular expression, but hey, why to write a regular expression if it's already written by someone.

So, I started googling up and wasn't successful in finding any regular expression for .Net engine which can strip a host url into subdomain, domain the way I expect. This led me to write my own regular expression.

I came up with following regular expression and the tool that I initially used for coming up with this regular expression was the RegexLib Tester

Regex 1:  ^([\w\.\-]+\.)*([\w\-]+\.)([\w]{2,3})(\.[\w]{2})?$
More...

Tags: ,

.Net | Utilities

Powered by BlogEngine.NET 2.0.0.36
Theme by Mads Kristensen | Modified by Mooglegiant

About Me

Welcome to my blog. My name is Nimesh and I work as a .Net Developer in one of the best city of the world, Gold Coast, QLD, Australia. more

Month List

Page List