I am using Autofac in my project,but i am unable to do a unit test on one particular class.
Consider the following Scenario :
//Class to be tested
public Class A
{
private SomeAutoFacClass B;
public void DoSomething()
{
B = scope.Resolve<ClassName>();// Resolve the object needed
// Do something with instance B
}
}
// Test class
public Class ATest
{
private A a;
[test]
public void TestMethod()
{
a.DoSomething();//*This method causes a null reference exception as it tries to resolve the objects*
}
}
In the code above,i am not able to unit test case due to the dependency injection which is only specific to that particular class.
how do i solve this? I also tried creating a autofaccontainer using Moq.
But that too fails.
The reason you are not able to test your class is because your class takes a dependency on your DI Container. This is an implementation of the Service Locator anti-pattern. It's an anti-pattern because:
the problem with Service Locator is that it hides a class' dependencies, causing run-time errors instead of compile-time errors, as well as making the code more difficult to maintain because it becomes unclear when you would be introducing a breaking change.
Instead, design your classes around
Constructor Injection in case the class is a component (a class that contains the applications behavior), where you inject the dependencies that a class directly needs through the constructor
Method Injection when the class is a data-centric object like an entity, which means the dependency is supplied to a the public method of such class, where the consuming class only uses that dependency, but not stores it.
Components are built-up by your DI Container and are registered in your Composition Root, while data-centric objects are newed up in code outside the Composition Root. In that case you need to pass along a dependency to an already constructed object.
In case you build and test a component, your code would typically look as follows:
public class ComponentA
{
private ClassName b;
public ComponentA(ClassName b)
{
this.b = b;
}
public void DoSomething()
{
// Do something with instance B
}
}
// Test class
public Class ATest
{
[test]
public void TestMethod()
{
// Arrange
B b = new FakeB();
var a = new ComponentA(b);
// Act
a.DoSomething();
// Assert
// Check whether be was invoked correctly.
}
}
In case you build and test a data-centric object that requires a dependency for one of its operations, your code would typically look as follows:
public class EntityA
{
public string Name { get; set; }
public int Age { get; set; }
public void DoSomething(ClassName b)
{
// Do something with instance B
}
}
// Test class
public Class ATest
{
[test]
public void TestMethod()
{
// Arrange
B b = new FakeB();
var a = new EntityA { Name = "Bert", Age = 56 };
// Act
a.DoSomething(b);
// Assert
// Check whether be was invoked correctly.
}
}
So to answer your initial question:
How do i unit test a class that uses IoC container classes
You don't. Your application code should not depend on the DI Container, because that leads to all kinds of complications such as being hard to test.
Using an IoC container you should aim to use IoC. Normally this is either constructor injection or property injection depending on what your container can support for auto-injection.
A pattern I use for this I call "lazy property injection" where I constructor-inject my container to act as a registry, then use the lazy resolution on property use..
What it looks like:
private readonly IoCContainer _container = null;
private IMyService _myService = null;
public IMyService MyService
{
get { return _myService ?? (_myService = _container.Resolve<IMyService>()); }
set { _myService = value; }
}
public MyClass( IoCContainer container)
{
if (container == null)
throw new ArgumentNullException("container");
_container = container;
}
Now when you go to test a method of this class, your test initializes your MyService with a Mock. When running under test, I have the IoCContainer initialized to a Mock() that throws if any .Resolve<> calls are made. This catches scenarios where your code under test might be modified to use a new dependency that hasn't been mocked out.
The benefit of this approach is that often a class will have several single-purpose methods, and by extension need a number of dependencies. In applications like web requests where maybe only one method is called, needing one dependency, the dependency resolution only retrieves the dependencies from the container that are needed, not all of them. (I.e. if you use constructor injection with 8 dependencies, all 8 need to be resolved at runtime, even if only 1 will be used.) This also simplifies unit testing to only mock out what you know will be needed rather than everything.
Related
This question already has answers here:
Dependency Injection Architectural Design - Service classes circular references
(4 answers)
Closed 3 years ago.
I know that others already had this very same issue, but I cannot find any statisfying solution, so I'm asking here for other ideas.
My business logic is contained in a service layer like that:
public class RoomService : IRoomService
{
private readonly IRoomRepository _roomRepository;
private readonly ICourseService _courseService;
public RoomService(IRoomRepository roomRepository, ICourseService courseService)
{
_roomRepository = roomRepository ?? throw new ArgumentNullException(nameof(roomRepository));
_courseService = courseService ?? throw new ArgumentNullException(nameof(courseService));
}
public Task DeleteRoomAsync(string id)
{
// Check if there are any courses for this room (requires ICourseService)
// Delete room
}
}
public class CourseService : ICourseService
{
private readonly ICourseRepository _courseRepository;
private readonly IRoomService _roomService;
public CourseService(ICourseRepository courseRepository, IRoomService roomService)
{
_courseRepository = courseRepository ?? throw new ArgumentNullException(nameof(courseRepository));
_roomService = roomService ?? throw new ArgumentNullException(nameof(roomService));
}
public Task GetAllCoursesInBuilding(string buildingId)
{
// Query all rooms in building (requires IRoomService)
// Return all courses for these rooms
}
}
This is just an example. There might be workarounds to avoid that the services depend on each other in this case, but I had multiple other situations in the past, where there wasn't any clean workaround.
As you can see, these two services depend on each other and dependency injection will fail because of the circular dependency.
Now I can imagine two ways to resolve this:
Solution 1
I could resolve the service-dependencies inside of the service methods that require them instead of injecting the service dependencies into the service constructor:
public class RoomService : IRoomService
{
private readonly IRoomRepository _roomRepository;
private readonly IServiceProvider _serviceProvider;
public RoomService(IRoomRepository roomRepository, IServiceProvider serviceProvider)
{
_roomRepository = roomRepository ?? throw new ArgumentNullException(nameof(roomRepository));
_serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider));
}
public Task DeleteRoomAsync(string id)
{
ICourseService courseService = _serviceProvider.GetRequiredService<ICourseService>();
// Check if there are any courses for this room (requires ICourseService)
// Delete room
}
}
Problem: This makes unit testing harder because I need to inject a mocked IServiceProvider that is able to resolve my ICourseService into the class constructor. Also it's not very clear when writing the unit tests, which services are required by each service method because that's completely implementation dependant.
Solution 2
The service method could require that the ICourseService is passed in from the controller as a method parameter:
public Task DeleteRoomAsync(ICourseService courseService, string id)
{
// Check if there are any courses for this room (requires ICourseService)
// Delete room
}
Problem: Now my controller needs to know about an implementation detail of the service method: DeleteRoomAsync requires an ICourseService object to do it's work.
I think that's not very clean because the requirements of DeleteRoomAsync might change in future, but the method signature should not.
Can you think of any alternative, cleaner solutions?
If your framework supports it, you can provide your injected dependencies as a Lazy<T> which defers resolution and allows you to have circular dependencies.
Here's what those service classes might look like:
class FooService : IFooService
{
protected Lazy<IBarService> _bar;
public FooService(Lazy<IBarService> bar)
{
_bar = bar;
}
public void DoSomething(bool callOtherService)
{
Console.WriteLine("Hello world. I am Foo.");
if (callOtherService)
{
_bar.Value.DoSomethingElse(false);
}
}
}
class BarService : IBarService
{
protected Lazy<IFooService> _foo;
public BarService(Lazy<IFooService> foo)
{
_foo = foo;
}
public void DoSomethingElse(bool callOtherService)
{
Console.WriteLine("Hello world. I am Bar.");
if (callOtherService)
{
_foo.Value.DoSomething(false);
}
}
}
The code that registers them does not require modification (at least not with Autofac):
public static IContainer CompositionRoot()
{
var builder = new ContainerBuilder();
builder.RegisterType<FooService>().As<IFooService>().SingleInstance();
builder.RegisterType<BarService>().As<IBarService>().SingleInstance();
builder.RegisterType<Application>().SingleInstance();
return builder.Build();
}
See a working example on DotNetFiddle.
If your framework does not support lazy injection like this, you can probably do the exact same thing using a factory (or any other pattern that defers resolution).
See also this answer which helped me come up with this solution.
The best solution is to avoid circular dependencies, of course, but it you're truly stuck, you can work around the issue by using property injection and RegisterInstance<T>(T t) (or its equivalent, if you're not using Autofac).
For example, if you have a FooService class and a BarService class that depend on each other, you can do this:
public static IContainer CompositionRoot()
{
var foo = new FooService();
var bar = new BarService();
foo.Bar = bar;
bar.Foo = foo;
var builder = new ContainerBuilder();
builder.RegisterInstance<IFooService>( foo );
builder.RegisterInstance<IBarService>( bar );
builder.RegisterType<Application>().SingleInstance();
return builder.Build();
}
This instantiates both services without their dependencies, and then sets them to each other afterward. By the time they are registered with the IoC container, their dependencies are completely set up.
See my Fiddle for a working example.
In provided examples, I would re-consider if you really have inter-service dependencies in those kind of situations:
Do you need logic contained in ICourseService in your RoomService implementation, or do you only need information from certain courses?
I would say that the latter one, so your real dependency could be ICourseRepository
with a method ICourseRepository.FindByRoom(Room room).
Do you need logic contained in IRoomService in your CourseService implementation, or do you only need existing rooms?
In this case, IRoomRepository could be enough.
However, it isn't always that easy and sometimes you really require logic implemented in Service layer, (validations, etc.). Trying to extract that behavior to shared classes rather than duplicating it or creating circular dependencies as mentioned can be preferrable in those scenarios.
When creating an application with Dependency Injection and it utilizes a framework for Dependency Injection such as Unity (or Ninject).
How do you initialize registering the interfaces to the container at the beginning all together and keep them available for the application to use throughout its running lifecycle of the application?
Do you need to pass the DI Container to each method that may utilize dependency injection, or is there some way to make the container globally accessible so that you can register them all together in the beginning and access them throughout running the application without having to continually pass them, and be able to utilize them when ever needed?
Environment: Visual Studio 2015, C#, Microsoft Unity (for DI Container)
Example Code
static void Main(string[] args)
{
// Make Unity resolve the interface, providing an instance
// of TrivialPursuit class
var diContainer = new UnityContainer();
diContainer.RegisterType<IGame, TrivialPursuit>();
var gameInstance = diContainer.Resolve<IGame>();
var xotherClass = new AnotherClass();
xotherClass.TestOtherClassOtherMethod();
}
------ Another class without context of the Dependency Injection Class ------
public void TestOtherClassOtherMethod()
{
IGame gameInstance = -- -Container is Not available to resolve from in this class ---
}
Reason: I don't want to need to pass every possible type that I may need later on to each class I load up, I will just want to use the instances when I need them. The more deeper I get into classes, later as the application becomes more complex, I won't want to pass down instances for each type up from the Main() method to each class.
A Dependency Injection (DI) container is just that. A framework for facilitating DI. You don't pass the container around in order to resolve instances of objects. You just request the type you need in your classes constructor and the DI framework will inject the appropriate dependency.
Mark Seemann has written a good book on dependency injection that I would recommend.
You register everything that'll need to be resolved with the container in the composition root. That is to say when your program starts up is when everything should be registered.
Let's say we have the following code:
public class MyClass
{
public Run()
{
var dependency = new Dependency1();
dependency.DoSomething();
}
}
public class Dependency1
{
public void DoSomething()
{
var dependency = new Dependency2();
dependeny.DoSomethingElse();
}
}
public class Dependency2
{
public void DoSomethingElse()
{
}
}
This gives us the above dependency chain: MyClass -> Dependency1 -> Dependency2.
The first thing we should do is refactor the classes to take their dependencies through their constructor and rely on interfaces rather than concretions. We can't inject dependencies unless there is a place to inject them (constructor, property, etc).
Here is the refactored code:
public interface IMyClass
{
void Run();
}
public interface IDependency1
{
void DoSomething();
}
public interface IDependency2
{
void DoSomethingElse();
}
public class MyClass : IMyClass
{
public readonly IDependency1 dep;
public MyClass(IDependency1 dep)
{
this.dep = dep;
}
public void Run()
{
this.dep.DoSomething();
}
}
public class Dependency1 : IDependency1
{
public readonly IDependency2 dep;
public MyClass(IDependency2 dep)
{
this.dep = dep;
}
public void DoSomething()
{
this.dep.DoSomethingElse();
}
}
public class Dependency2 : IDependency2
{
public void DoSomethingElse()
{
}
}
You'll notice the classes now all take their dependencies through their constructors and do not new up anything. Classes should only take in dependencies that they actually need. For example, MyClass does not NEED a Dependency2 so it doesn't ask for one. It only asks for a Dependency1 because that's all it needs. Dependency1 NEEDS Dependency2, not MyClass.
Now to wire it all up WITHOUT a container we would just new it all up in the composition root:
void Main()
{
var myClass = new MyClass(new Dependency1(new Dependency2()));
}
You can see how that could get cumbersom if we had tons of classes and depdencies. That's why we use a container. It handles all the depdency graph for us. With a container we'd rewrite it as follows:
void Main()
{
// the order of our registration does not matter.
var container = new Container();
container.Register<IDependency1>.For<Dependency1>();
container.Register<IDependency2>.For<Dependency2>();
container.Register<IMyClass>.For<MyClass>();
// then we request our first object like in the first example (MyClass);
var myClass = container.Resolve<IMyClass>();
myClass.Run();
}
In the second example the container will handle wiring up all the dependencies. So we never need to pass Depedency2 to MyClass and then to Depedency1. We only need to request it in Dependency1 and the container will wire it up for us like in the first example.
So in your example we would rewrite it like so:
static void Main(string[] args)
{
var game = new UnityContainer();
game.RegisterType<IGame, TrivialPursuit>();
game.RegisterType<IAnotherClass, AnotherClass>();
game.RegisterType<IYetAnotherClass, YetAnotherClass>();
var gameInstance = game.Resolve<IGame>();
// you'll need to perform some action on gameInstance now, like gameInstance.RunGame() or whatever.
}
public class Game : IGame
{
public Game(IAnotherClass anotherClass)
{
}
}
public class AnotherClass : IAnotherClass
{
public AnotherClass(IYetAnotherClass yetAnotherClass)
{
}
}
public class YetAnotherClass : IYetAnotherClass {}
In these cases there is no need to pass the container around. You register your dependencies with the container then request them in your classes constructors. If you wish to use the container in the class WITHOUT requesting it through the constructor then you are not doing DI you are just using the container as a singleton service locator. Something that should generally be avoided.
Container as a Service Locator
This should be generally avoided but if you want to use the container as a service locator you have two options:
1) Pass the container into your classes that need it through the constructor.
You can use the above examples for wiring your classes up for DI. But instead of requesting a dependency like IDependency in the constructor you just pass the container.
public class Game : IGame
{
public Game(IContainer container)
{
var blah = container.Resolve<IBlah>();
}
}
2) Request your container through a static class:
public static class ServiceLocator
{
private static IContainer container;
public static IContainer Container
{
get
{
if (container == null)
{
container = new Container();
}
return container;
}
}
}
Register everything as normal in your composition root using the ServiceLocator class. Then to use:
public class MyClass
{
public void DoSomething()
{
var blah = ServiceLocator.Container.Resolve<IBlah>();
}
}
So I have windsor set up and all of my services registered. I have a class that requires these services in the ctor, but this class isn't registered with windsor as it does not have an interface and I don't want to give it one for the sake of dependency resolution. What I'm really interested in, is having windsor resolve and inject my registered dependencies and hand me back an initialized class -- basically a factory.
The problem that I'm running into is that windsor throws because the dependent class has not been registered:
void Main()
{
var container = new WindsorContainer();
container.Register(Component
.For<ITestInterface>()
.ImplementedBy<TestImpl>()
.LifestyleTransient());
var c = container.Resolve<TestClass>(); // throws because TestClass isn't registered
c.Run();
}
public class TestClass
{
private ITestInterface _d;
public TestClass(ITestInterface d)
{
_d = d;
}
public void Run()
{
_d.Do();
}
}
public interface ITestInterface
{
void Do();
}
public class TestImpl : ITestInterface
{
public void Do()
{
Console.WriteLine("done");
}
}
What I don't want to end up doing, is something like this:
var dependency1 = container.Resolve<ITestInterface>();
var c = new TestClass(dependency1);
c.Run();
Because now we're in service locator territory. But more importantly, classes that have several dependencies...well that could get tedious.
How can I get windsor to have the desired factory effect? Or is this even possible with Windsor? I recall this being possble with Ninject.
So the popular response seems to be "Just register the component" which I really don't like at all because for such a simple use case, I could end up with a config class with hundreds of unnecessary registrations. That's kind of silly. So in the meanwhile, until I discover some built in functionality for this, I've create a cheesy extension that should land me somewhere in the middle. This extension simply takes the type, registers it for you and then tries to resolve it. That way, it's leveraging Windsor's own ctor resolution logic:
public static class WindsorExtentions
{
public static T Construct<T>(this IWindsorContainer container)
where T : class
{
if (!container.Kernel.HasComponent(typeof(T)))
container.Register(Component.For<T>());
var instance = container.Resolve<T>();
return instance;
}
}
What I would really like to do is register it, resolve it, then unregister it, but it appears that the RemoveComponent method has been removed in 3.0. This should be fine in the meanwhile. It obviously isn't all-inclusive with use cases, but when you have loads of proxy classes that have several required dependencies to be injected, I think this helps.
Usage:
var myClassWithDependencies = myContainer.Construct<MyClassWithDependencies>();
public class MyClassWithDependencies
{
public MyClassWithDependencies(
IFacebookClient facebookClient,
IGooglePlusClient googlePlusClient,
ITwitterClient twitterClient,
ISalesforceClient salesforceClient,
IReportRepository reportRepo,
IUserRepository userRepo)
{
}
}
I'm brand new to using Simple Injector although I have been using Ninject for a long time, so I am comfortable with DI in general. One thing that attracted me to want to use Simple Injector was the ease of use of Decorators.
I have been able to successfully use decorators with Simple Injector in all normal cases where the dependencies are resolved when the service is requested. However, I am having a hard time figuring out if there is a way to get my decorators applied in a case when the service must be constructed using a runtime value.
In Ninject, I could pass a ConstructorArgument to the kernel.Get<IService> request that could be inherited down the chain of N decorators all the way to the "real" implementing class. I cannot figure out a way to replicate that using Simple Injector.
I have put some very basic code below to illustrate. What I would want to do in the real world would be to pass an IMyClassFactory instance into other classes in my application. Those other classes could then use it to create IMyClass instances using the IRuntimeValue they would provide. The IMyClass instance they got from the IMyClassFactory would be decorated automatically by the registered decorators.
I know I could manually apply my decorator(s) in my IMyClassFactory or any Func<IMyClass> I could come up with, but I would like it to "just work".
I keep going around and around trying to abstract out the MyClass construction, but I can't figure out how to get it to resolve with the IRuntimeValue constructor argument and be decorated.
Am I overlooking an obvious solution?
using System;
using SimpleInjector;
using SimpleInjector.Extensions;
public class MyApp
{
[STAThread]
public static void Main()
{
var container = new Container();
container.Register<IMyClassFactory, MyClassFactory>();
container.RegisterDecorator(typeof (IMyClass), typeof (MyClassDecorator));
container.Register<Func<IRuntimeValue, IMyClass>>(
() => r => container.GetInstance<IMyClassFactory>().Create(r));
container.Register<IMyClass>(() => ?????)); // Don't know what to do
container.GetInstance<IMyClass>(); // Expect to get decorated class
}
}
public interface IRuntimeValue
{
}
public interface IMyClass
{
IRuntimeValue RuntimeValue { get; }
}
public interface IMyClassFactory
{
IMyClass Create(IRuntimeValue runtimeValue);
}
public class MyClassFactory : IMyClassFactory
{
public IMyClass Create(IRuntimeValue runtimeValue)
{
return new MyClass(runtimeValue);
}
}
public class MyClass : IMyClass
{
private readonly IRuntimeValue _runtimeValue;
public MyClass(IRuntimeValue runtimeValue)
{
_runtimeValue = runtimeValue;
}
public IRuntimeValue RuntimeValue
{
get
{
return _runtimeValue;
}
}
}
public class MyClassDecorator : IMyClass
{
private readonly IMyClass _inner;
public MyClassDecorator(IMyClass inner)
{
_inner = inner;
}
public IRuntimeValue RuntimeValue
{
get
{
return _inner.RuntimeValue;
}
}
}
Edit 1:
Ok, thanks to Steven for the great answer. It has given me a couple of ideas.
Maybe to make it a little more concrete though (although not my situation, more "classic"). Say I have an ICustomer that I create at runtime by reading a DB or deserializing from disk or something. So I guess that would be considered a "newable" to quote one of the articles Steven linked. I would like to create an instance of ICustomerViewModel so I can display and manipulate my ICustomer. My concrete CustomerViewModel class takes in an ICustomer in its constructor along with another dependency that can be resolved by the container.
So I have an ICustomerViewModelFactory that has a .Create(ICustomer customer) method defined which returns ICustomerViewModel. I could always get this working before I asked this question because in my implementation of ICustomerViewModelFactory I could do this (factory implemented in composition root):
return new CustomerViewModel(customer, container.GetInstance<IDependency>());
My issue was that I wanted my ICustomerViewModel to be decorated by the container and newing it up bypassed that. Now I know how to get around this limitation.
So I guess my follow-up question is: Is my design wrong in the first place? I really feel like the ICustomer should be passed into the constructor of CustomerViewModel because that demonstrates intent that it is required, gets validated, etc. I don't want to add it after the fact.
Simple Injector explicitly lacks support for passing on runtime values through the GetInstance method. Reason for this is that runtime values should not be used when the object graph is constructed. In other words, the constructors of your injectables should not depend on runtime values. There are several problems with doing that. First of all, your injectables might need to live much longer than those runtime values do. But perhaps more importantly, you want to be able to verify and diagnose your container's configuration and that becomes much more troublesome when you start using runtime values in the object graphs.
So in general there are two solutions for this. Either you pass on the runtime value through the method call graph or you create a 'contextual' service that can supply this runtime value when requested.
Passing on the runtime value through the call graph is especially a valid solution when you practice architectures like this and this where you pass on messages through your system or when the runtime value can be an obvious part of the service's contract. In that case it is easy to pass on the runtime value with the message or the method and this runtime value will also pass through any decorator on the way through.
In your case this would mean that the factory creates the IMyService without passing in the IRuntimeValue and your code passes this value on to the IMyService using the method(s) it specifies:
var service = _myServiceFactory.Create();
service.DoYourThing(runtimeValue);
Passing through the runtime value through the call graph however is not always a good solution. Especially when this runtime value should not be part of the contract of the message that is sent. This especially holds for contextual information use as information about the current logged in user, the current system time, etc. You don't want to pass this information through; you just want it to be available. We don't want this, because this would give an extra burden to the consumers of passing the right value every time, while they probably shouldn't even be able to change this information (take the user in who's context the request is executed for instance).
In that case you should define service that can be injected and allows retrieving this context. For instance:
public interface IUserContext {
User CurrentUser { get; }
}
public interface ITimeProvider {
DateTime Now { get; }
}
In these cases the current user and the current time aren't injected directly into a constructor, but instead these services are. The component that needs to access the current user can simply call _userContext.CurrentUser and this will be done after the object is constructed (read: not inside the constructor). Thus: in a lazy fashion.
This does mean however that the IRuntimeValue must be set somewhere before MyClass gets invoked. This probably means you need to set it inside the factory. Here's an example:
var container = new Container();
var context = new RuntimeValueContext();
container.RegisterSingle<RuntimeValueContext>(context);
container.Register<IMyClassFactory, MyClassFactory>();
container.RegisterDecorator(typeof(IMyClass), typeof(MyClassDecorator));
container.Register<IMyClass, MyClass>();
public class RuntimeValueContext {
private ThreadLocal<IRuntimeValue> _runtime;
public IRuntimeValue RuntimeValue {
get { return _runtime.Value; }
set { _runtime.Value = value; }
}
}
public class MyClassFactory : IMyClassFactory {
private readonly Container _container;
private readonly RuntimeValueContext context;
public MyClassFactory(Container container, RuntimeValueContext context) {
_container = container;
_context = context;
}
public IMyClass Create(IRuntimeValue runtimeValue) {
var instance = _container.GetInstance<IMyClass>();
_context.RuntimeValue = runtimeValue;
return instance;
}
}
public class MyClass : IMyClass {
private readonly RuntimeValueContext _context;
public MyClass(RuntimeValueContext context) {
_context = context;
}
public IRuntimeValue RuntimeValue { get { return _context.Value; } }
}
You can also let the MyClass accept the IRuntimeValue and make the following registration:
container.Register<IRuntimeValue>(() => context.Value);
But the disallows verifying the object graph, since Simple Injector will ensure that registrations never return null, but context.Value will be null by default. So another option is to do the following:
container.Register<IMyClass>(() => new MyClass(context.Value));
This allows the IMyClass registration to be verified, but will during verification still create a new MyClass instance that is injected with a null value. If you have a guard clause in the MyClass constructor, this will fail. This registration however disallows MyClass to be auto-wired by the container. Auto-wiring that class can come in handy when you've got more dependencies to inject into MyClass for instance.
Rhino Mock Experts please help.
Below Example of rhino mock is working fine.
internal class TestClass
{
private ITestInterface testInterface;
public TestClass(ITestInterface testInterface)
{
this.testInterface = testInterface;
}
public bool Method1(int x)
{
testInterface.Method1(x);
return true;
}
}
[TestClass]
public class UnitTest2
{
[TestMethod]
public void TestMethod1()
{
ITestInterface mockProxy = MockRepository.GenerateMock<ITestInterface>();
TestClass tc = new TestClass(mockProxy);
bool result = tc.Method1(5);
Assert.IsTrue(result);
mockProxy.AssertWasCalled(x => x.Method1(5));
}
}
Problem i am facing as per above code is i need to create a constructor in all child classes like this:-.
internal class testclass1 : TestClass
{
protected testclass1(ITestInterface testInterface) : base(testInterface)
{
}
}
Is there any workaround for it as i am having around 50 child classes?
As mentioned in my comment to your question, this isn't really an issue caused by mocking or unit testing. It is a natural consequence of using constructor injection (ie. providing Dependencies as constructor arguments). An alternative is to use property injection, that is, creating a writable property by which you can set your ITestInterface object, like so:
public class TestClass {
public ITestInterface FooBar {protected get; set; }
}
This way, all derived classes have access to FooBar without the need to create their own constructor that passes the ITestInterface through to the base class.
However, this has other consequences: constructor injection typically expresses mandatory dependencies. Without that dependency, the class won't work. Property injection, however, is often used to express optional dependencies or a way to override the default behavior. This distinction isn't set in stone, though, and if your really have dozens of classes deriving from TestClass constructor injection can become a real burden to maintain.
If an object requires constructor arguments it is very obvious to the user that he must pass the required dependencies. With property injection it is much easier to forget to set the property to properly set up the object (if the dependency is required). Also, with constructor injection you only need to check if the dependency has been provided once (in the constructor), while with property injection it's more likely that you need to check the validity of the dependency each time you use it.
Again, if using constructor injection results in a maintenance nightmare because you have many sub classes, property injection is still a viable option despite what I wrote before.
You could additionally express the required property dependencies by using an initialization method like:
public static class TestClassInitializer{
public T Initialize<T>(this T t, ITestInterface dependency) where T:TestClass{
t.FooBar = dependency;
return t;
}
}
If you can force yourself to construct objects like this:
var tc = new DerivedTestClass().Initialize(mockTestInterface);
You have a single point where you can modify required dependencies. If you now need a second dependency, just update the signature to include the second dependency
public static class TestClassInitializer{
public T Initialize<T>(this T t, ITestInterface dependency, IOtherDependency other) where T:TestClass{
t.FooBar = dependency;
t.OtherDependency = other;
return t;
}
}
And all places where you call Initialize will break at compile time. This is a good thing(!) because you need to provide the required dependencies. However, you only need to update those places, not the 50 derived classes to add an additional dependency. If you had used constructor injection you what have needed to update all 50 classes and all places where you instantiate them.
Also: if you know that your derived classes only have a default constructor, you can create a factory method for all classes :
public static class TestClassFactory{
public static T Create<T>(ITestInterface dep1, ITestInterface dep2) where T :TestClass, new(){
return new T{FooBar = dep1, OtherDependency = dep2};
}
}
Instead of new DerivedTestClass().Initialize(...) you can now use TestClassFactory.Create<DerivedTestClass>(mockedDep1, mockedDep2);. You can make the actual constructors (protected) internal if you want as long as the TestClassFactory is in the same assembly (or in an assembly that can access the internal constructors through InternalsVisibleTo).
All this is less of an issue if you use a dependency injection framework/IoC container, as it won't forget to provide the dependencies once setup correctly.