What is the right way to read a different set of properties when running unit tests

java, tdd

Solution

Dependency Injection (DI). Your ConnnectionFactories are dependencies. DI will allow you to send in an instance of a ConnectionFactory as a constructor parameter. IN this way, the unit test would send in a MockConnectionFactory instance, and the live code would send in a DefaultConnectionFactory instance.

public class ConnectionFactoryProvider {
    public static IConnectionFactory getConnectionFactory(IConnectionFactory connectionFactory) {
    //use the connectionFactory
    }
}

//unit test
ConnectionFactoryProvider cfp = new ConnectionFactoryProvider(aMockConnectionFactoryInstance);

//live code
ConnectionFactoryProvider cfp = new ConnectionFactoryProvider(aDefaultConnectionFactoryInstance);

Hope that helps.

P.S. I'm a C# developer, but I think that syntax is more or less the same for you in Java.

Problem

I want to configure certain classes (FactoryProviders) to behave differently when they are being used in unit tests. ``` public class ConnectionFactoryProvider { public static IConnectionFactory getConnectionFactory() { //return MockConnectionFactory if running in test mode and //DefaultConnectionFactory is running in production mode } } ``` I need to return a different ConnectionFactory depending on whether the code is running in test mode (unit test) or production mode. What is the right way to achieve this ? A few possible solutions come to mind... but is any one of them a widely followed idiom ? - System property through JVM args such that the value will be different when running in production and test modes. - Keep the fully qualified name of the factory in a properties file, and ensure that when running in test mode a different property file is available on the file system. This would be easy to do with Maven because we can control the classpath order when running in the test phase, but I am not sure if it is possible to achieve when running unit tests from within Eclipse. - Configure the ConnectionFactoryProvider in the tests setup method so it returns the MockConnectionFactory

Original source

Related problems