I am currently working on code coverage for a project that I haven't worked on. Here is sample code of it:
public class JmsMessageGateway extends AbstractMessageGateway {
private CachingConnectionFactory cachingConnectionFactory;
public void send() {
createAmqpConnection();
...//try send message
if(//if failed) {
restartConnection();
}
}
private void createAmqpConnection() throws JMSException {
amqpJmsConnection = cachingConnectionFactory.createConnection();
amqpJmsConnection.start();
}
private void restartConnection() throws JMSException {
recreateConnection();
}
private void recreateConnection() throws JMSException {
cachingConnectionFactory = cachingConnectionFactory();
createAmqpConnection();
}
private CachingConnectionFactory cachingConnectionFactory() {
CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
connectionFactory.setTargetConnectionFactory(jmsConnectionFactory());
return connectionFactory;
}
private JmsConnectionFactory jmsConnectionFactory() {
... //do some configuration stuff
return connectionFactory;
}
In order to unit test recreateConnection, my unit test is doing something like this:
@Before
public void setup() throws JMSException {
...
when(connectionFactory.createConnection()).thenReturn(amqpJmsConnection);
...
}
So when send()
is called, amqpJmsConnection
is set by cachingConnectionFactory.createConnection();
. This .createConnection()
will fail if not mocked since connection properties are test values.
Problem is when I test restartConnection. In cachingConnectionFactory()
, it reinitialize CachingConnectionFactory
object and set to local cachingConnectionFactory
object, so when createAmqpConnection();
is called, cachingConnectionFactory
object is NOT mocked object in cachingConnectionFactory.createConnection();
.
I tried Powermock but was having problems, and I don't prefer using Powermock. How can I test restartConnection()
without refactoring the class (which I am thinking about doing it).
Edit: I tried creating builder pattern for CachingConnectionFactory
so I can mock each time cachingConnectionFactoryBuilder.build()
is called, but it doesn't make sense to create builder just for unit test..