So here it is – the first real post in our series on DotNetNuke Patterns and Practices. How do we make our “Controllers” testable.
Historically, DotNetNuke has used a “Repository” style for manipulating entities in the business layer (rather than an Active Record style) – a lightweight Entity class – usually suffixed with Info, and a Repository class which has traditionally used Controller as a suffix.
This naming strategy was present initially in the iBuySpy Portal Starter-Kit upon which DotNetNuke is based. Thus, for instance, if the business layer needs to model Task objects, there will be a TaskInfo entity and a TaskController repository class.
Back in 2002/3 when DotNetNuke was first created, developers were not so concerned about whether they could write Unit Tests, so the pattern of use was that whenever a “controller” was needed it was constructed on the fly. If that controller in turn needed to call a 2nd controller then it was also constructed on the fly.
The problem, from a modern perspective is that it is difficult to write Unit Tests using this pattern, as there are unknown dependencies that cannot be mocked or faked.
Dependency Injection
One of the ways to solve this is to use Dependency Inversion. This principle is one (the D) of the SOLID Principles of Object Oriented Design espoused by “Uncle” Bob Martin and others (we will review these principles in future articles in this series). The “Dependency Inversion Principle” says that any dependencies should be based on abstractions not concretions.
Dependency Injection supports this by injecting any dependency in the form of an Interface (or abstract base class), usually through the Constructor.
So if ControllerA has a dependency on IControllerB then ControllerA’s constructor should look like the following:
private IControllerB _controllerB;
public ControllerA(IControllerB controllerB)
{
_controllerB = controllerB;
}
The class that is constructing a ControllerA would need to also construct a concrete implementation (ControllerB) of IControllerB and pass it as a parameter.
IControllerB controllerB = new ControllerB();
ControllerA controllerA = new ControllerA(controllerB);
In a Unit Test, the dependent interface can then be mocked, using a mocking framework like Moq or RhinoMocks or faked by creating a FakeControllerB which has a known behavior.
Dependency Injection Containers
We can make this simpler by using a Dependency Injection Container. DotNetNuke has a simple Container and we can use this container to register all of our controllers. This can reduce some of the plumbing that we have to do.
For example, we can create an instance of ControllerB and add it to the Container.
ComponentFactory.RegisterComponentInstance<IControllerB>(new ControllerB);
Now we can modify the ControllerA class by adding a second constructor with no parameters.
public ControllerA()
: this(ComponentFactory.GetComponent<IControllerB>())
{
}
With these changes in place we can go back to our original pattern of constructing an instance of ControllerA.
var controllerA = new ControllerA();
When writing Unit Tests the dependency on IControllerB can be resolved by mocking or faking IControllerB and adding the mock (or fake) to the Container as part of the test setup.
There are some examples in the core of this pattern.
Service Location
An alternative approach to Dependency Injection is to use Service Location. In Service Location we call some service to locate an instance of the Interface that we need.
The Container in DotNetNuke is actually an example of Service Location.
var b = ComponentFactory.GetComponent<IControllerB>();
In 6.2 we have introduced an abstract base ServiceLocator class that manages the service location.
public abstract class ServiceLocator<TContract, TSelf> where TSelf : ServiceLocator<TContract, TSelf>, new()
{
private static TContract _instance;
private static bool _isInitialized;
protected static Func<TContract> Factory { get; set; }
public static TContract Instance
{
get
{
if (!_isInitialized)
{
if (Factory == null)
{
var controllerInstance = new TSelf();
Factory = controllerInstance.GetFactory();
}
_instance = Factory();
_isInitialized = true;
}
return _instance;
}
}
public static void SetTestableInstance(TContract instance)
{
_instance = instance;
_isInitialized = true;
}
protected abstract Func<TContract> GetFactory();
}
How this works is best shown with an example. In the CTP we have refactored the RoleController to use this new service location pattern.
We have extracted an interface – IRoleController – from the original RoleController class:
public interface IRoleController
{
int AddRole(RoleInfo role);
void DeleteRole(RoleInfo role);
RoleInfo GetRole(int portalId, Func<RoleInfo, bool> predicate);
IList<RoleInfo> GetRoles(int portalId);
IList<RoleInfo> GetRoles(int portalId, Func<RoleInfo, bool> predicate);
IDictionary<string, string> GetRoleSettings(int roleId);
void UpdateRole(RoleInfo role);
void UpdateRoleSettings(RoleInfo role, bool clearCache);
}
Next we implemented a concrete implementation of the Interface – RoleControllerImpl (which is too long to show in its entirety here).
Finally we created a class which inherits from the new ServiceLocator class – TestableRoleController.
public class TestableRoleController : ServiceLocator<IRoleController, TestableRoleController>
{
protected override Func<IRoleController> GetFactory()
{
return () => new RoleControllerImpl();
}
}
This now works in a similar way to the way we use our providers. To call a method on the RoleController, we call the Instance method, which returns the current Instance of the interface.
TestableRoleController.Instance.AddRole(role);
The Instance property of the abstract ServiceLocator base class will return an instance of the interface (IRoleController). By default the GetFactory method is setting the internal instance to be the concrete implementation (RoleControllerImpl) but the base class also has a method SetTestableInstance. We can now use this method to change the internal instance to a Mock or Fake, allowing us to test methods which call the TestableRoleController.
We believe that this is a simple pattern which will encourage creation of Testable Controllers, and as we move closer to the 6.2 Release expect to see more of the core converted to this pattern. Of course, the existing methods will be retained for binary compatibility, but we are also taking the opportunity to clean up some of our old APIs.
Note: The usage of the TestableRoleController is temporary – ultimately RoleController will be refactored to inherit from the new ServiceLocator base class.