Pages

Sunday, October 27, 2013

Fluent controller builder updates

Yesterday I blogged about a fluent controller builder that I put together. You can read about it here. While building further tests using this controller builder I soon got into trouble. My initial design catered well for simple controllers which always have default constructors. So following code worked

var documentController = Build.Controller<DocumentController>()
                              .Having(b =>
                                {
                                    b.PostRequest().At("http://localhost/api/content");
                                    b.UsingDefaultRoute().HavingRouteData("controller", "document");
                                });

 A problem with this code is that it is creating an instance of the controller for me. This works fine when controller has a default constructor. As complexity of my application grew, I soon needed to inject various dependencies into my controller and above code stopped working. To fix the problem, I have introduced a new class that lets you configure a controller instance for use in unit testing. So you control the instantiation part and pass the instance of a configuration class that would do rest of the magic. Here is how the new code looks

documentRepository = Substitute.For<IRepository<Document>>();
idGenerator = Substitute.For<IGenerateId>();
urlBuilder = Substitute.For<IBuildUrl>();

documentController = new DocumentController(documentRepository, idGenerator, urlBuilder);

Configure.Controller(documentController).AsHaving(b =>
             {
                    b.PostRequest().At("http://localhost/api/content");
                    b.UsingDefaultRoute().HavingRouteData("controller", "document");
             });

Here my controller has three dependencies for which I want to inject stubs instead of real objects. This is easy because now I can create my own instance of controller and send it in to new Configure class that would prepare my controller for unit testing.

The nuget package has been updated to include this new change. You can find the details here

No comments:

Post a Comment