Skip to main content

Posts

Showing posts from September, 2010

Why you can’t assert a return type of an MVC Controller Action using reflection!

I recently asked this question on Stack Overflow.  I was using reflection and MethodInfo to confirm that a controller contained an action with the required method parameters.  If one was found, this would then allow my code to unit test that the correct Action Filter Attributes were being assigned to the controller action (so a particular action could only respond to an HTTP GET or POST as an example).   This was all working fantastically well but I made the mistake of trying a unit test too far and was surprised by the outcome.  I was attempting to assert/validate the return type was of the desired type (e.g. ActionResult or JSONResult) but my assertion was failing.  In the debug watch window I could see the return parameter was of the desired type but it was wrapped up inside a RuntimeType.  No amount of fiddling / casting would get the test to pass.  Another SO user helpfully pointed out that an MVC action might actually return RedirectToRouteResult, etc. so the wrapping was a requ…

Team Foundation Server 2010 Licensing

UPDATE: Since putting this article together MS have released their VS2010 and MSDN Licensing White Paper, which whilst it confirms all of the following should be used in preference to this information.Original Article:Firstly, a bit of a disclaimer - the following are just my observations / opinions only and should not be used to plan any purchase or decision.  I also have no association with Microsoft or any reseller.As part of a new role I've recently been looking into the costs associated with rolling out TFS 2010 and whilst Microsoft seem to be making their product structure / licensing easier if the confusion surrounding TFS is anything to go by then they've still got a little more to do. There are two main ways to obtain TFS:As part of VS2010 + MSDN, orAs a stand alone product.As far as I can ascertain both include exactly the same version of TFS. Along the VS2010 MSDN subscription a developer receives 1 Client Access License (CAL) for use with TFS.  This allows that dev…

Injecting HttpContextBase into an MVC Controller

It is a shame that when the ASP.NET MVC framework was released they did not think to build IoC support into the infrastructure. All the major components of the MVC engine appear to magically inherit instances of HttpContext and it’s related objects – which can cause no end of problems if you are trying to utilise Unit Testing and IoC. Reading around various articles on the subject just to get around this one problem requires the implementation of several different concepts and you are still left with a work around. The code below, along with the other links referenced in this article is my stab at resolving the issue. There’s probably nothing new here, but it does attempt to relate all the information needed to do this for Castle Windsor. The overview is that all controllers will need to inherit from a base controller, which takes an instance of HttpContext into it’s constructor. It then overrides the property HttpContext in the main controller class, supplying it’s own version…

Controller Factory for Castle Windsor v2.5.0, with HttpContext Resolution/Injection

The code below defines an object that holds an instance of the Castle Windsor container and sets it up to handle all requests to resolve ASP.NET MVC Controllers.  It also includes code to inject instances of HttpRequest and HttpContextBase.  This means that you can define injected objects that contain references to HttpContextBase in their constructors (which can be your MVC controllers) and they will receive populated instances of these objects.  It is worth noting that if you reference an instance of HttpContext that has not been resolved / injected by your IoC container then there is a high likely hood that you will end up with two or more separate instances which will cause problems (see this article on Injecting into Action Filter Attributes that can suffer this issue).Please feel free to use this code and let me know if you run into any issues or have recommendations on how it could be improved.public classWindsorControllerFactory : DefaultControllerFactory { IWindsorContainer Con…

IoC and MVC Action Filter Attributes

As I’ve previously mentioned anyone starting out with IoC and ASP.NET MVC quickly encounters problems injecting HttpContext and related classes into controllers, etc.  A similar issue surrounds Action Filter Attributes but is not limited to just HttpContext as objects inheriting from ActionFilterAttribute must contain a “parameter less” default constructor.  Without a “parameter less” constructor these objects can not be created when used to decorate a class or action declaration.  Also, the MVC engine is responsible for the creation of the attributes when they are decorating class/action declarations, completely by-passing the IoC container and any hope of using property injectors.  The only way to gain access to the IoC container is to make sure that it is available through a static public object (such as global.asax) and reference the container directly in the filter constructor.  This is not ideal, but checking other articles on the web, there does not appear to be any better solu…

Updating NServiceBus to use another version of Castle Windsor

Having recently taken a look at NServiceBus, the first obstacle that I encountered was that it was not compatible with the version of Castle Windsor which we were using.  Luckily due to the design of NServiceBus adding a new version of an IoC framework is relatively painless if you follow a couple of basic steps and follow the format laid out by the existing framework.  Whilst the NServiceBus documentation say what you need to do, it does not say why or how.  It probably took longer than it should for me to realise that I could easily download the source code and modify the existing Castle Windsor object builder instance for the version that we were using.  As recommended within NServiceBus I created a new VS project called “NServiceBus.ObjectBuilder.CastleWindsor.2.5.0” adding a reference to the Castle binaries we would be using (as you may have guessed from the project name, that was v2.5.0).  The project only needed two classes defined (Windsor250ObjectBuilder & ConfigureWindso…

Unit Testing: Selecting an Action from an MVC Controller

To fully test an MVC web site it is important to test (in isolation) the following:
Behaviour of controller actionsBehaviour of any custom action filters.The decoration of action filter attributes on controller actions.To test the 3rd point, you must use reflection to select the desired action from the controller.  The following method takes an action name and a Tuple array of "Type" and "String". Used together this combination should be enough to isolate a desired action.  Note: an empty tuple array is used to define no input parameters, which a null tuple array specifies that this shouldn't be used to restrict the action (in this case the action name must be null)publicMethodInfo SelectAction(Controller controller, string actionName, Tuple[] expectedParameters = null){var methods = controller.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance).Where(mi => mi.Name.Equals(actionName));if (expectedParameters != null) methods = methods.Where(mi …

Injecting AutoMapper with IoC

Update - 14th February 2016:
Looking in my blog stats, this continues to be one of my most popular articles, so it is most definitely worth an update. As of v4.2.0 Automapper has been updated to remove the static implementation. I've not had chance to play with the new version yet but I would imagine this version will now work with any IoC container you wish to use it with.Original Article:
The main “Mapper” class of the AutoMapper framework is a static class which does make the initial testing and usage really easy but quickly causes problems if you’re using an Inversion of Control framework such as a Castle Windsor.  Also being static it is far harder to abstract the AutoMapper framework out of any unit tests using mocking frame such as MOQ.  As a final point for all these reasons using AutoMapper directly could cause problems in the future if it was decided to switch to another mapping framework.
The following code handles all of the above concerns / issues by wrapping the Aut…

Playing with AutoMapper

In my current role we have come across a requirement to map message objects to more complex domain entities.  As anyone that has done this previously will quickly tell you, manually writing code to do this is very boring and repetitive.  With very limited time and resources, that effort could be better spent elsewhere on the project.  As it seemed very simple to set up and start using we’ve decided to use AutoMapper.

Configuring / Using
Setting up a basic mapper is as simple as:
Mapper.CreateMap<Source,Target>();var target = Mapper.Map<Source,Target>(source); The call to CreateMap only needs to be made once for the duration of the AppDomain, calls to Map are then made as needed.
As was as direct property name mapping several other more complex mappings are provided “out of the box”.  This includes flattening properties of child objects into named properties in the target object.   AutoMapper also provides several different methods to provide custom mappings either inline in t…

Mocking HttpCookieCollection in HttpRequestBase

When unit testing ASP.NET MVC2 projects the issue of injecting HttpContext is quickly encountered.  There seem to be many different ways / recommendations for mocking HttpContextBase to improve the testability of controllers and their actions.  My investigations into that will probably be a separate blog post in the near future but for now I want to cover something that had me stuck for longer than it probably should have.  That is how to mock non abstract/interfaced classes within HttpRequestBase and HttpResponseBase – namely the HttpCookieCollection class.   The code sample below illustrates how it can be used within a mocked instance of HttpRequestBase.  Cookies can be added / modified within the unit test code prior to being passed into the code being tested.   After it’s been called, using a combination of MOQ’s Verify and NUnit’s Assert it is possible to check how many times the collection is accessed (but you have to include the set up calls) and that the relevant cookies have …