So I have a helper method that looks something like the following:
private D GetInstanceOfD(string param1, int param2)
{
A a = new A();
B a = new B();
C c = new C(a,b, param1);
return new D(c, param2);
}
It’s just a convenient helper method for which I can call to grab a particular object that I need rather then to remember which dependencies I need to hook up to get the object I require.
My first question here is: should methods like these be tested? The only reason I can think of to want to test these type of methods would be to make sure that the correct dependencies are used and are set up correctly.
If the answer to the first question is yes, my second is: how? I am currently using NUnit and RhinoMocks and am trying to work out how this method has to be refactored to be testable (well, and whether something like this should be tested!); dependency injection obviously would not work here as this method actually creates the dependencies!
Or is using this method bad practice and I should be doing something like the following:
D d = new (new C(new A(), new B(), "string"), 1024);
First, the method is private and, so, normally I would say that testing is probably not necessary for that method directly. Even if it were a helper method for real code, instead of a helper for your tests, you may want to only test it indirectly through the public interface.
Second, if you do want to test it — and perhaps anyway — you should consider using factories to do the object creation rather than directly instantiating the objects. Using a factory, in conjunction with interfaces, will allow you to abstract the dependencies out. Simply inject the factory into the constructor of the class containing this method and use it as a property within this method to create the proper objects. If you go this route, you may also find that the factory is also the place for the logic to create D.
This would definitely be the direction I would take if the code were production code. Example below: