AutoFixture AutoMoq Cast a mocked object as an interface - c#

I hope someone can give me some ideas.
I need to create a mocked object that satisfies the following:
It implements the interface IEntity.
It uses the base implementation I already have in EntityBase.
The properties are auto generated with AutoFixture.
I have tried several alternatives and I ended with this code:
fixture.Customize(new AutoConfiguredMoqCustomization());
fixture.Customize<IEntity>(c => c.FromFactory(
() => fixture.Create<Mock<EntityBase>>().As<IEntity>().Object));
However, I obtain the following exception:
Mock type has already been initialized by accessing its Object property. Adding interfaces must be done before that. :(

You could use a TypeRelay to tell AutoFixture that requests for IEntity should be satisfied by creating instances of EntityBase:
fixture.Customizations.Insert(0, new TypeRelay(typeof(IEntity), typeof(EntityBase)));
Now, every time AutoFixture has to create an instance of IEntity, it will instead create an instance of EntityBase which, in turn, will be handled by Moq thanks to the AutoConfiguredMoqCustomization.
Relays are pretty handy and there are a few of them built-in. In fact, they enable the whole auto-mocking functionality by relaying requests for interfaces and abstract classes to a mocking library.

Related

How can I avoid modifying IMyClass and MyClass when I want to add a new method?

We use Mock objects that rely on dependency injection, interfaces, etc in order to unit test our web service. It always seems like the process of making modifications could be streamlined a bit, if (for example) an interface could be generated from a concrete class. If I add a new public property DeleteUser to MyClass, it's clear that it should also go into IMyClass.
Is there such a way to streamline this process? Or is our method of testing itself outdated perhaps?
As already stated by #yanyankelevich the new method/property is added to the interface first. Next, you open a class implementing the original interface, and VS (or is it actually ReSharper?) will offer to implement the missing members, i.e. it adds the property / function with a throw new NotImplementedException() in the body. Now replace that with your code. That's it.
There is a way, when using Typemock Isolator you can mock concrete classes with no need of creating an interface before doing so.

How to instruct Ninject to use a factory method for any requested subtype of a given type?

I have a base Dto type where I have several common logic and code (change notifications, validations, etc.). Due to technical reasons whenever I have to create an instance of a concrete DTO type like PersonDTO I have to use a factory method.
var personDto = Dto.Create<PersonDTO>();
// or a non-generic variant like
var personDto = Dto.Create(typeof(PersonDTO));
Now how could I ask Ninject to use this factory method whenever I need inject any Dto descendant? I mean something like
Bind<Dto>().ToMethod(ctx => Dto.Create(ctx.Request.Service));
but which could get applied to not only the base Dto requests but also to every request for any Dto descendant type.
I know I could probably use the conventions Ninject extension's "for all ..." kind of feature, but I'd rather like a way without yet another library if possible.
For every type which needs to be resolvable (IResolutionRoot.Get<SomeType>()), there needs to be a binding, for example:
Bind<Dto>().To..
Bind<DtoBla>().To..
except in case you'll do a binding with multiple types such as:
Bind<Dto,DtoBla>().To...
this overload is specifically useful when you want to bind multiple types to the same instance, for example if you want to have a singleton FooBar : IFoo, IBar resolve as IFoo and IBar.
Now in case you have to do a lot of very similar bindings, Ninject.Extensions.Conventions is just a library to make the task easier for you. You don't need to use it, you can also program type detection (using reflection) and binding creation yourself.
The reflection part has been covered many times over and over on stackoverflow, see for example:
Generating a list of child classes with reflection in .NET 3.5
Register all declared child classes of a class in C#
Get all derived types of a type
Search an assembly for all child types?
Of course, if you don't want to use Ninject.Extensions.Reflection, you can also just go look at its source code to see how it's done and copy the relevant parts! ;-)

Resolve more than one object with the same class and interface with Simple Injector

I am trying to migrate from Unity to Simple Injector in my new project. It is so much faster than Unity that I have to give it a shot. I have had a few bumps, but nothing I could not work around. But I have hit another one with "Look-up by Key"
I have read this where the creater of simple injector states his belief that you should not need to resolve more than one class per interface.
I must be a poor programmer, because I have done that with Unity (which supports it very well) and want to do it in my current project.
My scenario is that I have an IRepository interface. I have two separate repositories I want to abstract using the IRepository interface. Like this:
container.Register<FirstData>(() => new FirstData());
container.Register<IRepository>(
() => new GenericRepository(container.GetInstance<FirstData>()));
container.Register<SecondEntities>(() => new SecondEntities());
container.Register<IRepository>(
() => new GenericRepository(container.GetInstance<SecondData>()));
IRepository/GenericRepository is a fairly common abstraction, but you can only have one in SimpleInjector
In Unity I could register both of my repositories and then setup my constructor injection to inject the instance that I needed. This was accomplished using a key for the instance. (I did not need to do a Resolve call in my normal code nor add a dependency to Unity outside my setup.)
With simple injector this does not work. But, for better or worse, the owner of Simple Injector thinks this feature is a bad idea.
NOTE: The author's "in app" system looks like it uses a string key for look-up, but it still requires a different class each time (DefaultRequestHandler, OrdersRequestHandler and CustomersRequestHandler). I just have a GenericRepostory which allows me to abstract my repository methods regardless of what I am connected to.
I suppose I could inherit my GenericRepostory for each time I want to instantiate it. Or have it take a random type parameter that I don't need. But that muddles my design, so I am hoping for another way to do it.
So are there any work arounds that don't have me creating bogus types to differentiate between my two IRepository/GenericRepository instances?
We ended up changing our Generic Repository to look like this:
/// The Type parameter has no funcionality within the repository,
/// it is only there to help us differentiate when registering
/// and resolving different repositories with Simple Injector.
public class GenericRepository<TDummyTypeForSimpleInjector> : IRepository
(We added a type parameter to it).
We then created two dummy classes like this (I changed the names of the classes to match my example):
// These are just dummy classes that are used to help
// register and resolve GenericRepositories with Simple Injector.
public class FirstDataSelector { }
public class SecondDataSelector { }
Then I can register them like this:
container.Register<FirstData>(() => new FirstData());
container.Register(() => new GenericRepository<FirstDataSelector>
(container.GetInstance<FirstData>()));
container.Register<SecondEntities>(() => new SecondEntities());
container.Register(() => new GenericRepository<SecondDataSelector>
(container.GetInstance<SecondData>()));
(Note the generic type param on the GenericRepository and that I do not register it as an IRepository. Those two changes are essential to making this work.)
This works fine. And I am then able to use that registration in the constructor injection of my business logic.
container.Register<IFirstBusiness>(() => new FirstBusiness
(container.GetInstance<GenericRepository<FirstDataSelector>>()));
container.Register<ISecondBusiness>(() => new SecondBusiness
(container.GetInstance<GenericRepository<SecondDataSelector>>()));
Since my Business classes take an IRepository it works fine and does not expose the IOC container or the implementation of my repository to the business classes.
I am basically using the Type parameter as Key for lookup. (A hack I know, but I have limited choices.)
It is kind of disappointing to have to add dummy classes to my design, but our team decided that the drawback was worth it rather than abandoning Simple Injector and going back to Unity.
Your own answer is actually quite good, but its unfortunate that you see the generic type parameter as a dummy; you should make it first class citizen of your design:
public interface IRepository<TData> { }
public clss GenericRepository<TData> : IRepository<TData>
{
public GenericRepository(TData data) { }
}
This way you can simply register them as follows:
container.Register<IRepository<FirstData>, GenericRepository<FirstData>>();
container.Register<IRepository<SecondData>, GenericRepository<SecondData>>();
Your business classes can in that case simply depend on the generic IRepository<FirstData> and IRepository<SecondData> and can simply be registered as follows:
container.Register<IFirstBusiness, FirstBusiness>();
container.Register<ISecondBusiness, SecondBusiness>();
Note how the registrations given here don't use any lambdas. Simple Injector can find this out for you. This makes your DI configuration much simpler, more readable, and especially: more maintainable.
This way you make your design very explicit and unambiguous. Your design was ambiguous because you had a single (non-generic) IRepository interface that should be mapped to several implementations. Although this doesn't have to be bad in all cases, in most cases this ambiguity can and should be prevented, because this complicates your code and your configuration.
Further more, since your generic GenericRepository<T> now maps to the generic IRepository<T> we can replace all Register<IRepository<T>, GenericRepository<T>>() registrations with a single line:
// using SimpleInjector.Extensions;
container.RegisterOpenGeneric(typeof(IRepository<>),
typeof(GenericRepository<>);
To take it even one step further, your business classes could perhaps as well benefit from generic typing. Take a look at this article for instance where each business operation gets its own class but all business operations are hidden behind the same generic ICommandHandler<TCommand> abstraction. When you do this, all business classes can be registered with a single call:
container.RegisterManyForOpenGeneric(typeof(ICommandHandler<>),
typeof(ICommandHandler<>).Assembly);
This call searches the supplied assembly for implementations of the ICommandHandler<TCommand> interface and registers each found implementation in the container. You can add new pieces of business logic (use cases) without having to change the configuration. But this is just one of the many advantages of having such abstraction over your business logic. An other great advantage is that it makes adding cross-cutting concerns (such as logging, transaction handling, security, audit trail, caching, you name it) much easier to implement.

How to configure the factory to generate the object?

Maybe the title is not so clear. Let me clarify what I'm trying to accomplish.
I have to base classes:
BaseProperties
BaseProblem
BaseProperties contains data about the generation of math problems. For example, in the image above, BasicAdditionProperties contains Addend1 and Addend2, this two objects know about the range of the generated value to represent a BasicAdditionProblem.
So, this is just an idea.. I guess I supposed to pass the abstract class to a factory, and this one should generate the problem (in this case BasicAdditionProblem).
I have read, it's recomended pass these values as the base class. And my main doubt is, when I pass the object BaseProperties to the factory, all the time do I have to cast the object?
Or what ideas can I implement to model this scenario? Or do I have to have a static Factory where maintain and be used as mapping to the concrete factories?
Thanks in advance.
Define an abstract CreateProblem() in the BaseProperties class. This method can be used generically to allow each concrete Properties subclass to provide its own Factory method.
This is similar to using an instance of WebRequest subclass and calling GetResponse() on it and it then returns the coresponding subclass of WebResponse.
This distributed abstract factory approach allows you to add property/problem pairs easily to the system because the code to map the two is solely contained in those two classes.
You could also use a full Abstract Factory implementation where you have PropertyProblemFactory that defines a CreateProperties() and a CreateProblem(). So in your example you would have AdditionFactory that knows how to create the matching set. But this forces you to define an additional class for each Property/Problem pair. It also works best when you have a class that uses the current/selected PropertyProblemFactory, creates a Properties with it, and then immediately uses that same PropertyProblemFactory factory to create the matching Problem. Once you let go of the reference to the factory and solely have just a reference to the Properties, it is harder to re-locate the right factory to create the Problem. (This can be addressed with yet another class to map object types to factories, but the complexity rises. So the first appoach I suggested is better in this kind of situation).
There are multiple solutions for this. It just depends on how you want to program it.
abstract methods in the abstract class must be handled in all classes that inherit from the abstract class. This way you can easily call abstract methods in the factory without casting.
However when you need to use lots of data from just one specific class then it would not be wise to make abstract methods for it and you should just simply cast the object.
So it all depends on how much classes inherit from BaseProperties and how much data in those classes are the same.

Type constraints on constructor for factory method

I found that my design is wrong and asking you how solve my problem.
So my case:
I'm writing factory method, for classes, witch was derived from my special base class. So I wrote
public T MyFactory<T>() where T:MyBaseClass
But my the main work of my factory method is getting some special parameters and passing it to constructor of new object. MyBaseClass has this constructor:
public MyBaseClass(MySpecParam param){...}
But there is no guarantee that type T, derived from MyBaseClass, has such a constructor.
The only solution I see, is to add new() constraint and virtual Init method to MyBaseClass, so that the factory can safely create a new object of type T, and then init it with MySpecParam object.
But, MyBaseClass has such design, so it's completely unusable if it is not inited with MySpecParam. And user can create MyBaseClass with parameterless constructor and get completely invalid, not initialized, object. I think it's not good.
There is no way to add new(MySpecParam) constraint.
How must I design my objects, constructors and factory method?
If each class has only one public constructor, you can find that by reflection, determine what parameters it takes, and supply the appropriate values when you call the constructor (still through reflection).
Otherwise, I presume you have a finite set of constructor signatures. In that case, you'll need some way of determining which constructor to call; the decision may be based in part on the identity of the type argument T.
EDIT
If you're not willing to use reflection for the reasons outlined in your comment, then the answer is more or less "no, you can't do that." Michael Yoon suggests an IoC framework, which of course uses reflection and is subject to run-time errors as well. In my experience (with Castle Windsor), performance has never been a problem, and run-time errors as the result of misconfiguration are caught almost immediately in the development cycle.
Another thought; this may not be helpful, but it might be worth considering. You could use a Func<T> to create the instance, or even have overloads of the factory method for different types of Func<T, TOut>, Func<T1, T2, TOut>, etc, where you call
var obj = FactoryMethod<SomeType>(() => new SomeType(23));
Alternatively, consider the abstract factory pattern.
Sounds like a problem for an IoC container. If your factory used a container like StructureMap or Unity, your constructor issue would no longer be a concern. The factory would ask StructureMap (for example) to resolve MyBaseClass, and it would return an instance your MyBaseClass using the greediest constructor, recursively building all of its dependencies and so forth.
Constructors are not inherited, nor are they allowed on interfaces. This means that each class's constructor are specific only to that class. That also means that a subclass could be made of your base class that doesn't have a constructor that matches your pattern. If you want to have a standard way of configuring your objects, I think an abstract Init(foo, bar, baz), on your base class, similar to your idea, is the best solution. You could also implement internal logic that throws if the objects are accessed before they are initialized, but unfortunately, you won't be able to enforce that at compile time.

Categories

Resources