Search code examples
mavenunit-testingactivemq-classic

Unit Test against ActiveMQ


I use maven to run my unit tests. Every time i have to remember to start ActiveMQ first because the unit test need to send JMS message to Queue and consume it for assertion. I wonder is there some maven plugin to automatically launch the ActiveMQ for unit testing?

In short, is it possible to launch ActiveMQ before running unit testing? I googled and found some tips. But according their suggestions, I should run a mvn command to launch the ActiveMQ which is not an automatic way to run unit test.


Solution

  • A shorthand to test AMQ flows from java is to connect to vm://localhost?broker.persistent=false.

    That will create and start a new broker (if there is no one running). You will need no boiler plate code to create, configure and start/stop the broker.

    However, that assumes you have no major configuration changes from the default values you want to test. In that case you may want to configure and start the broker manually.

    You can do so by starting the broker in a @Before method in your Junit test.

    i.e.

    BrokerService broker;
    
    @Before
    public void setupAMQ(){
    
       broker = new BrokerService();
       TransportConnector connector = new TransportConnector();
       connector.setUri(new URI("tcp://localhost:61616"));
       broker.addConnector(connector);
       // More config here!
       broker.start()
    }
    
    @After
    public void tearDownAMQ(){
       broker.stop();
    }
    

    Read more about the topic.