Let’s suppose I’ve to test this Java ClassA that depends on the difficult to instantiate ClassB:
public class ClassA
{
public ClassA()
{
String configFile = "config_file.xml";
// I have to pass configFile to instantiate ClassB.
// And for example if configFile does not exists in the testing machine?
// Wouldn't it be easier to have an empty constructor for classB to test ClassA?
ClassB classB = new ClassB(configFile);
}
// ...
}
ClassB:
class ClassB
{
ClassB(String configFile)
{
// Set up configs.
}
// ...
}
Is it bad practice to create an empty constructor inside classB only for testing purposes?
Or is it better to rewrite a simplified mock ClassB for that?
It seems like yours would be a suitable scenario for IoC and Dependency Injection, using something like Spring or Guice.
That way
ClassAwould just declare that it “needs” an instance ofClassB, and your IoC container would wire up and construct the required dependencies.However, if you don’t want to get a framework in the way, you can solve it by extracting an interface contract out of
ClassB, and haveClassAdepend on that, and receive a implementation to that contract in its constructor.For example:
Have
ClassBimplement it:And use it, like:
That way, in your unit test, you can pass an instance you determine in your test, such as a Mock, and you can test accordingly, without having to modify your code for
ClassB.The bottom line is, that you should try to avoid creating additional constructors and such solely for testing purposes.