Using Ninject, I have a factory registered like this:
kernel.Bind<IMyFactory>().ToFactory();
Where IMyFactory looks something like this:
public interface IMyFactory
{
T CreateInstance<T> where T : MyBaseClass;
}
The reason for this is that classes derived from MyBaseClass have their own dependencies and I needed to be able to create instances of those classes from their types which I do like this:
MethodInfo mi = factory.GetType().GetMethod("CreateInstance");
MethodInfo generic = mi.MakeGenericMethod(type);
var param = (MyBaseClass)generic.Invoke(factory, null);
Where factory is the instance of IMyFactory created by Ninject and type is the type of MyBaseClass derived class I want to create. This all works really well.
The problem is that I'd like to be able to unit test this using the testing framework in Visual Studio and Moq, but I can't figure out a good way to mock IMyFactory.
Currently I have this:
analyticFactory = new Mock<IAnalyticFactory>();
analyticFactory.Setup(d => d.CreateAnalytic<MyFirstClass>()).Returns(new MyFirstClass(userService.Object));
analyticFactory.Setup(d => d.CreateAnalytic<MySecondClass>()).Returns(new MySecondClass(userService.Object, someOtherServiceMock.Object));
// repeat for as many classes as would usually be handled by IMyFactory
Obviously this is really tedious (I have a few dozen classes to do). Is there a better way to do it?
Aucun commentaire:
Enregistrer un commentaire