Reputation: 12453
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 ?
Upvotes: 3
Views: 135
Reputation: 328624
I use the following two approaches in my code applications:
Read a system property that can contain a symbolic name. In production, the default is used. The symbolic name is mapped to a config file that explains what the name means.
That way, you can have as many config files as you want, you can add configs at runtime (no code changes necessary to enable more logging in production to trace a bug).
Example: Name of system property is db.config
. Symbolic names are h2
, it
, prod
(default). The config files are on in ${configPath}/db-${db.config}.xml
Read config based on the property user.name
. That allows you to easily give each developer their own config. If there is no config file with that name, a default config is read (or the default is always read and then merged with an optional per-user config)
Upvotes: 1
Reputation: 570
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.
Upvotes: 5