Using Autofac and Moqs with Delegate Factories - c#

I am trying to unit test a class that uses factory injection. I have a class that instantiates two copies of the same object (with different config) to control hardware. I'm trying to test the behaviour of the classes while simulating the hardware calls.
I've injected a set of factory delegates into the constructors so that the class can instantiate the hardware classes as required. However I just can't work out how to control or create factory methods within the Autofac.Extras.Moq package. It seems that this functionality isn't supported in the package.
I'm looking for an equivalent call to :
mock.Provide<IHWController>(//created by factory delegate)
I want to create a specific mock object with behaviour, based on the parameters used to instantiate the HWcontroller. Is what I'm trying to do even possible?
class SystemUnderTest
{
SystemUnderTest(Ia a, Ib b, Ic c,
/** 15 other things **/
Func<Func<Uri, IHwController>, HwType, IHwManager> HwManagerFactory,
Func<Uri, IHwController> HwControllerFactory)
{
}
}
class HwManager()
{
public Func<HwType, Func<Uri, HwController>, HwManager> Factory;
public HwManager(HwType type, Func<Uri, HwController> ControlFactory)
{
//Constructor
}
}
The code I'm unit testing creates Managers of controllers. The controller is the hardware layer, but I'm testing complex (coupled) behaviour inside the manager. Therefore, I'm trying to work out how to mock the Func<Uri, HwController> ControlFactory so that it returns my setup mock objects so that I can probe the behaviour of the manager.
My system under test creates a concrete instantiation of the HWManager. I realise in a perfect scenario I would test the HwManager and SUT separately, but I'm specifically testing the integration of the two components.
I'd like to configure the autofac to control the delegate factory. If this isn't possible, then I can manually setup the SUT, but then I don't get any value from the autofac helper.

I usually just create a Func that returns my mocked instance e.g.
var controller = mock.Provide<IHWController>();
var manager = new HwManager(something, (uri) => controller);
If the factory is expressing "given a Uri I will provide a controller", the lamda in my example above satisfies that statement.
As an aside, you should express your factories using interfaces, not concrete classes. It makes it a lot harder to unit test when the factories are producing concrete classes instead of interfaces (which can always be mocked) e.g.
// IHwController is the product of the factory instead of HwController
public HwManager(HwType type, Func<Uri, IHwController> ControlFactory)

If anyone gets stuck on this in the future, the key is to create a func that matches the constructor func, customised to provide the appropriate mocks on each invokation (e.g. via an internal counter).
You can then use the mock.Provide() syntax, providing a func that matches the constructor func with your created func above. This will then be invoked correctly allowing you to control the mocks appropriately.

Related

Mock IOC Unity Object Creation call

public class ExcelHelper : IExcelHelper
{
private ICustomLoadRepository _customLoadRepository;
public ExcelHelper(IUnityContainer unityContainer)
{
_customLoadRepository= unityContainer.Resolve<ICustomLoadRepository>();
}
}
We have started using RhinoMocks to Unit test our code.
Not sure how to mock the code line
_customLoadRepository = unityContainer.Resolve<ICustomLoadRepository>();
We do not want it be resolved by passing from constructor parameter as number of such parameters sometimes reach more than 7-8 on classes.
This appears to be an XY problem.
That said, it is generally considered a bad practice to inject the container as a dependency into any class because it defeats the purpose of using dependency injection. Such designs have more in common with the Service Locator pattern. Which is considered, in this context, an anti-pattern.
You should instead practice Explicit Dependencies Principle
Methods and classes should explicitly require (typically through method parameters or constructor parameters) any collaborating objects they need in order to function correctly.
...
Classes with explicit dependencies are more honest. They state very clearly what they require in order to perform their particular function.
public class ExcelHelper : IExcelHelper {
private readonly ICustomLoadRepository customLoadRepository;
public ExcelHelper(ICustomLoadRepository customLoadRepository) {
this.customLoadRepository = customLoadRepository;
}
//...
}
this can easily be tested by injecting a mock of the abstracted dependency using Rhino Mocks or any other mocking framework.
public void Some_unit_test() {
//Arrange
var stubCustomLoadRepository = MockRepository.GenerateStub<ICustomLoadRepository>();
stubCustomLoadRepository.Stub(_ => _.SomeCustomLoadMethod()).Return("Some value");
var classUnderTest = new ExcelHelper(stubCustomLoadRepository);
//Act
//...exercise class under test
//Assert
//...
}
As for your statement about having many constructor parameters,
We do not want it be resolved by passing from constructor parameter as the number of such parameters sometimes reach more than 7-8 on each classes
I consider this a code smell. This often indicates that your class is trying to do too many things. A violation of the Single Responsibility Principle (SRP).
So by all indications it appears you have a design issue. Review you classes and try refactoring them with aggregated dependencies. Consider following a more SOLID design principle.

SimpleInjector ctor injection mix registered types and simple values

How do I register types which take another registered type as a parameter and also simple types (like an integer)?
public interface IDeviceManager
{
// implementation omitted.
}
public class DeviceManager : IDeviceManager
{
public DeviceManager(IDeviceConfigRepository configRepo, int cacheTimeout)
{
// implementation omitted
}
}
I do have a container registration for the IDeviceConfigRepository. That's ok. But how do I create an instance of DeviceManager with the configured dependency and passing along an integer of my choice in composition root?
I thought about creating a factory.
public class DeviceManagerFactory : IDeviceManagerFactory
{
private readonly Container _container;
public DeviceManagerFactory(Container container)
{
_container = container;
}
public DeviceManager Create(int minutes)
{
var configRepo = _container.GetInstance<IDeviceConfigurationRepository>();
return new DeviceManager(configRepo, minutes);
}
}
This is pretty simple.
However now I do not have a registration for DeviceManager which is the type I ultimately need. Should I change these dependencies to the factory instead?
public class ExampleClassUsingDeviceManager
{
private readonly DeviceManager _deviceManager;
public ExampleClassUsingDeviceManager(DeviceManager deviceManager, ...)
{
_deviceManage = deviceManager;
}
// actions...
}
For this to work and to avoid circular dependencies I would probably have to move the factory from the "application" project (as opposed to class libraries) where the composition root is to the project where the DeviceManager is implemented.
Is that OK? It would of course mean passing around the container.
Any other solutions to this?
EDIT
In the same project for other types I am using parameter objects to inject configuration into my object graph. This works OK since I only have one class instance per parameter object type. If I had to inject different parameter object instances (for example MongoDbRepositoryOptions) into different class instances (for example MongoDbRepository) I would have to use some kind of named registration - which SimpleInjector doesn't support. Even though I only have one integer the parameter object pattern would solve my problem. But I'm not too happy about this pattern knowing it will break as soon as I have multiple instances of the consuming class (i.e. MongoDbRepository).
Example:
MongoDbRepositoryOptions options = new MongoDbRepositoryOptions();
MongoDbRepositoryOptions.CollectionName = "config";
MongoDbRepositoryOptions.ConnectionString = "mongodb://localhost:27017";
MongoDbRepositoryOptions.DatabaseName = "dev";
container.RegisterSingleton<MongoDbRepositoryOptions>(options);
container.RegisterSingleton<IDeviceConfigurationRepository, MongoDbRepository>();
I am excited to hear how you deal best with configurations done at composition root.
Letting your DeviceManagerFactory depend on Container is okay, as long as that factory implementation is part of your Composition Root.
Another option is to inject the IDeviceConfigRepository into the DeviceManagerFactory, this way you can construct a DeviceManager without the need to access the container:
public class DeviceManagerFactory : IDeviceManagerFactory {
private readonly IDeviceConfigurationRepository _repository;
public DeviceManagerFactory(IDeviceConfigurationRepository repository) {
_repository = repository;
}
public DeviceManager Create(int minutes) {
return new DeviceManager(_repository, minutes);
}
}
However now I do not have a registration for DeviceManager which is the type I ultimately need. Should I change these dependencies to the factory instead?
In general I would say that factories are usually the wrong abstraction, since they complicate the consumer instead of simplifying them. So you should typically depend on the service abstraction itself (instead of depending on a factory abstraction that can produces service abstraction implementations), or you should inject some sort of proxy or mediator that completely hides the existence of the service abstraction from point of view of the consumer.
#DavidL points at my blog post about runtime data. I'm unsure though whether the cacheTimeout is runtime data, although you seem to be using it as such, since you are passing it in into the Create method of the factory. But we're missing some context here, to determine what's going on. My blog post still stands though, if it is runtime data, it's an anti-pattern and in that case you should
pass runtime data through method calls of the API
or
retrieve runtime data from specific abstractions that allow resolving runtime data.
UPDATE
In case the value you are using is an application constant, that is read through the configuration file, and doesn't change during lifetime of the application, it is perfectly fine to inject it through the constructor. In that case it is not a runtime value. There is also no need for a factory.
There are multiple ways to register this in Simple Injector, for instance you can use a delegate to register the DeviceManager class:
container.Register<DeviceManager>(() => new DeviceManager(
container.GetInstance<IDeviceConfigRepository>(),
cacheTimeout: 15));
Downside of this approach is that you lose the ability of Simple Injector to auto-wire the type for you, and you disable Simple Injector's ability to verify, diagnose and visualize the object graph for you. Sometimes this is fine, while other times it is not.
The problem here is that Simple Injector blocks the registration of primitive types (because they cause ambiguity) while not presenting you with a clean way to make the registration. We are considering (finally) adding such feature in v4, but that doesn't really address your current needs.
Simple Injector doesn't easily allow you to specify a primitive dependency, while letting the container auto-wire the rest. Simple Injector's IDependencyInjectionBehavior abstraction allows you to override the default behavior (which is to disallow doing this). This is described here, but I usually advice against doing this, because it is usually requires quite a lot of code.
There are basically two options here:
Abstract the specific logic that deals with this caching out of the class and wrap it in a new class. This class will have just the cacheTimeout as its dependency. This is of course only useful when there actually is logical to abstract and is usually only logical when you are injecting that primitive value into multiple consumers. For instance, instead of injecting a connectionstring into multiple classes, you're probably better of injecting an IConnectionFactory into those classes instead.
Wrap the cacheTimeout value into a complex data container specific for the consuming class. This enables you to register that type, since it resolves the ambiguity issue. In fact, this is what you yourself are already suggesting and I think this is a really good thing to do. Since those values are constant at runtime, it is fine to register that DTO as singleton, but make sure to make it immutable. When you give each consumer its own data object, you won't have to register multiple instances of those, since they are unique. Btw, although named registations aren't supported, you can make conditional or contextual registrations using RegisterConditional and there are other ways to achieve named registrations with Simple Injector, but again, I don't think you really need that here.

Where should I store collections of objects to facilitate DI / testing?

I am trying to figure out where to store collections of objects that are retreived from a database that are necessary for the application to function. For example, I am trying to re-design a reporting application that uses Report and Parameter objects. These objects are stored in a database in XML format. At the simplest level, a collection of the definitions could be stored as a Dictionary<string, string> (object key, object definition XML).
I want to implement a factory pattern to handle the creation of these objects from their XML definitions.
IReport GetReport(string reportName)
IParameter GetParameter(string parameterName)
These methods require the factory to store the collections of reports and parameters.
So, my questions are:
Should the factory store the collection of objects at all or should it only be responsible for creating the objects from the definition, changing the method to IReport GetReport(string reportDefinition)
If the factory should store the objects, should I simple inject the collections into the constructor of the factory class?
Unit testing - If I go the route of #2, I suppose I would just inject my test collections into the factory, right?
You can structure this in many ways which all adhere to the SRP (Single Responsibility Principle).
One way is as follows: have one interface, IReportLoadingService, with a method which takes in the report identifier, and returns the IReport instance.
An implementation of this IReportLoadingService can have an IReportDefinitionRetrievalService as a dependency, e.g.
public class ReportLoadingService : IReportLoadingService
{
private readonly IReportDefinitionRetrievalService _definitionService;
public ReportLoadingService(IReportDefinitionRetrievalService definitionService)
{
_definitionService = definitionService;
}
public IReport GetReport(string reportName)
{
var reportDefinition = definitionService.GetDefinition(reportName);
return GenerateReportFromDefinition(reportDefinition);
}
private IReport GenerateReportFromDefinition(string definition)
{
// Logic to construct an IReport implementation
}
}
The live implementation of the IReportDefinitionRetrievalService will access the database and return the XML. Now your ReportLoadingService has the responsibility of populating IReport instances while another service has the responsibility of actually obtaining the report definition.
For unit testing, you can create a Mock of the IReportDefinitionRetrievalService which does whatever you want (e.g. looking up the definition in a dictionary). Take a look at Moq for a good mocking framework. It will allow you to do things like this:
[Test]
public void GetReportUsesDefinitionService()
{
var mockDefinitionService = new Mock<IReportDefinitionRetrievalService>();
mockDefinitionService.Setup(s => s.GetDefinition("MyReportName")).Returns("MyReportDefinition");
var loadingService = new ReportLoadingService(mockDefinitionService.Object);
var reportInstance = loadingService.GetReport("MyReportName");
// Check reportInstance for fields etc
// Check the definition service was used to load the definition
mockDefinitionService.Verify(s => s.GetDefinition("MyReportName"), Times.Once());
}
Your application should be persistent ignorant, so your report factory (or repository would be a better term for a facade over a data store, actually it's a Data Access Object not really a repository) should not take a report definition format.
The Get method should take a unique identifier for the report (should this be report name?) and return a DTO type that has all of the values for the report entity.
You can use an abstract factory pattern to have different implementations of your repository, one that does the XML deserialization, and a mock implementation for unit tests.
Your repositories don't need to store the collections in memory if you already have a database as the data store, although you might want to add caching to your repository, which again is easier to switch out if your application is working against abstractions.
1.Should the factory store the collection of objects at all or should it only be responsible for creating the objects from the definition,
changing the method to IReport GetReport(string reportDefinition)
None of the above. A factory is a concrete implementation selector. It's implemented as a static method which instantiates a concrete object based upon the input. You have done the job of decoupling correctly with an interface and a name. Stop there.
static IReport GetReport(string reportName)
IReport concreteReport = Factory.GetReport("myReportName")
Testing a factory via a unit test is straight forward. You can create an array of report names and check the IReport is the correct implementation via reflection or some arbitrary known Assertion. Dependency Injection is a different topic alltogether.

How to create testable code using .Net IO classes?

I want to create unit testable code that mocks out the calls to the .Net System.IO classes, so I can really unit test instead of depending on the filesystem.
I am using the SystemWrapper classes to wrap around the BCL classes.
I am trying to get a simple example working to see whether a file exists.
The problem I am having is that injecting the dependency in the class doesn't work because instantiating the dependency (through StructureMap) requires knowing what constructor parameter to pass, which won't be available at that time, also there is no default constructor.
sample code:
// don't want to create dependency here like so
//IFileInfoWrap fileInfoWrap = new FileInfoWrap(filename);
// using service locator (anti-pattern?!) since it can't be
// injected in this class
var fileInfoWrap = ObjectFactory.GetInstance<IFileInfoWrap>(
new ExplicitArguments(new Dictionary<string, object>
{
{"fileName", filename}
}));
Console.WriteLine("File exists? {0}", fileInfoWrap.Exists);
What I don't like is that the dependency is not injected, ObjectFactory should not be here (but I see no other way of creating this).
The ExplicitArguments makes it messy and the argument-name is a magic-string.
For me to get this to work StructureMap config class needs to know explict which constructor I want to use ( I just started with StructureMap so this might not be the right way to set it up):
ObjectFactory.Initialize(x =>
{
x.Scan(scan =>
{
scan.AssembliesFromPath(".");
scan.RegisterConcreteTypesAgainstTheFirstInterface();
scan.WithDefaultConventions();
});
// use the correct constructor (string instead of FileInfo)
x.SelectConstructor(() => new FileInfoWrap(null as string));
// setting the value of the constructor
x.For<IFileInfoWrap>()
.Use<FileInfoWrap>()
.Ctor<string>("fileName")
.Is(#".");
});
Does anyone found a better solution to create testable code against the System.IO classes?
I know part of the problem is in the design of the System.IO classes.
An approach I've used very successfully is to roll my own proxy types for the types found in System.IO and other parts of the FCL. E.g. I want to take a dependency on System.IO.File. I create a library called System.IO.Proxies and add a concrete type File and an interface IFile. The interface IFile exposes members equivalent to all those which I require from System.IO.File and the concrete type implements those members by doing nothing other than forwarding method calls to System.IO.File. System.IO.Proxies is excluded from unit testing and code coverage. In my consuming assembly, I take a dependeny only on System.IO.Proxies and, specifically, I only take a dependency on IFile. This way I can mock this dependency easily and attain 100% code coverage for my consuming assembly.
(Note that this is a tailored version of my more general answer to a previous question.)

IoC with static and dynamic dependencies

I'm trying to implement IoC in my app. I have this model:
interface IService;
interface IComponent;
class Service : IService
Service()
class Component : IComponent
Component(IService service, object runtimeValue) { }
At some point in my app I need to get a IComponent. My app uses a IoC container (Unity). I can register Service with the container but I can't do the same for Component b/c of its dependency runtimeValue. According to this I have to use a factory and inject that wherever I need to get a IComponent:
interface IComponentFactory
IComponent CreateComponent(object runtimeValue)
class ComponentProvider : IComponentProvider
ComponentProvider(IComponentFactory factory) { }
IComponent CreateAndCacheComponent(object runtimeValue) {
_component = factory.CreateComponent(runtimeValue)
return _component
}
// other methods
I must be able to register the factory with the container, so it must have only static dependencies. At the same time it must be able to provide a service instance of type IService required to create a component.
Here is the factory implementation. The only thing I could think of was to use a Func<> delegate as dependency:
class ComponentFactory : IComponentFactory
ComponentFactory(Func<IService> serviceFactoryDelegate)
IComponent CreateComponent(object runtimeValue) {
return new Component(serviceFactoryDelegate.Invoke(), runtimeValue)
}
... and register the delegate with the container as static factory, so that it calls back the container to resolve the service (I'm using Unity 1.2 on .net 2.0):
Container
.Configure<IStaticFactoryConfiguration>()
.RegisterFactory<Func<IService>>(container => (Func<IService>)container.Resolve<IService>)
Now I can use the container to resolve a ComponentProvider and get a component based on a runtime value:
// this happens inside CompositionRoot
provider = Container.Resovle<IComponentProvider>()
component = provider.CreateAndCacheComponent("the component")
Now I have some questions about this:
I'm not happy that the factory calls new Component(...). Isn't this poor man's DI?
Does the Hollywood principle still stand when using Func<IService> on factory's constructor? I mean, it ultimately calls container.Resolve<>... kind of like SL. The only difference is the code is in the container registration part of the app rather than inside the factory class.
Is there anything (else) wrong with this implementation, as far as DI and IoC are concerned?
It's a big step away from Poor Man's DI, but it would be nice if you didn't have to change this factory method every time a new dependency gets added to the Component's constructor.
This isn't a problem per se. Think of it like you're injecting an anonymous factory class. It can still be mocked for unit testing, and the bindings can be changed, so you're still getting the benefits of DI. But it is an added layer of abstraction which is probably not necessary. You can still avoid it in this case by injecting the IService directly into the factory, rather than a Func.
Typically when using dependency injection, you want to inject services rather than values. The fact that you're finding that you have to have both may indicate that you need to reconsider your class's API. For example, maybe you should be passing the value in to the methods on the class rather than the constructor. It's hard to say what the best approach would be without knowing more details.
No, it isn't. The whole purpose of a factory is to create an instance of a concrete class.
Basically, yes, but as I already asked in my comment, I don't see why this is necessary. You could inject an instance of IService directly
It's a bit more complicated than it needs to be. Why the double redirection IComponentProvider -> IComponentFactory? It looks like IComponentFactory doesn't add any benefit.
Implement ComponentProvider like this:
class ComponentProvider : IComponentProvider
{
ComponentProvider(IService service) { _service = service; }
IComponent CreateAndCacheComponent(object runtimeValue) {
_component = new Component(_service, runtimeValue);
return _component;
}
This would give you the following benefits:
You get rid of the unnecessary interface IComponentFactory along with the corresponding implementation.
No need to register a factory for IService
Generally speaking, how you implement this it depends on what you really need:
"runtimeValue" can be the same throughout the runtime, e.g. a connection string that is read from the settings. In that case, there would be no need for a factory / provider, you could simply new up the instance and register it with the container. Everyone who needs an IComponent requests one in the constructor instead of the provider.
You would only implement a factory and pass that as a dependency around if the "runtimeValue" really changes between calls to CreateAndCacheComponent.
To question 1: there is nothing wrong with calling new in the factory. You have isolated instantiation to one place in your application; you just made that one place the factory instead of the container.
If you ever needed to mock or change implementations, you would just mock or change the factory implementation, rather than the Component alone.

Categories

Resources