Recently I had to write some code for accessing a JMS queue through JNDI. The code itself is no rocket science.. (don’t forget the try {…} finally { close()} stuff!)
Properties env = new Properties(); env.put(INITIAL_CONTEXT_FACTORY, getJndiInitialContextFactoryClassName()); env.put(PROVIDER_URL, getJndiUrl()); Context context = new InitialContext(env); this.queue = (Queue) context.lookup(getQueueName()); QueueConnectionFactory queueConnectionFactory = (QueueConnectionFactory) context.lookup(getJndiQueueConnectionFactoryName()); this.queueConnection = queueConnectionFactory.createQueueConnection(); this.queueConnection.start(); this.queueSession = this.queueConnection.createSession(false, Session.AUTO_ACKNOWLEDGE); MessageConsumer consumer = this.queueSession.createConsumer(queueEnvironment.getQueue()); Message message = consumer.receive(timeout);
Anyway, I wanted to test it. Some googling learned me the existence of mockEJB. A lightweight mock framework for testing EJB. The project itself seems to be dead for quite a while, but it does what I need so I went for it.
This is what I had to write to set up my queue in my mock environment:
@BeforeClass
public static void startUpClass() throws NamingException, JMSException {
MockContextFactory.setAsInitial();
InitialContext context = new InitialContext();
MockContainer mockContainer = new MockContainer(context);
mockContainer.deploy(new MDBDescriptor("MyQueueConnectionFactory", "MyQueueName", new DummyMessageBean()));
}
@AfterClass
public static void tearDownClass() {
MockContextFactory.revertSetAsInitial();
}
Pretty easy !!
But, I found a little bug in the mockEJB code. (while closing a connection that is already closed, a null pointer exception is thrown in the MockConsumer class). I patched it and you can find the patch ..::here::..