Advisory Messages to the rescue

The most crucial part of software development is testing. It should ensure us, that our code is correct, works according to given specs, etc. There are many kinds of tests: unit tests, integration, functional. In general you should try to test the smallest possible subset of your code and be able to check the state of the objects after the test.

This seems as rather easy task, but what if you have an integration end-to-end test to perform? In most cases asserting state in integration test is rather hard due to multiple systems interoperability. Let’s focus on a specific situation.

What I needed to do the other day was write some integration test for Jms based system. The processing pipeline is easy:

  • fetch object from DB
  • process it
  • publish on JMS

some other system (X-system) polls JMS:

  • if message is found
  • fetch it (message disappears from the JMS queue)
  • do sth with it
  • Looks simple but since I didn’t have any sane access to the X-system I wanted to be sure that my object was actually put into the queue. It was not acceptable to subscribe to the queue and fetch that object in my test – it would dusrupt the flow of the whole process.

    Fortunately I’ve been using ActiveMQ and since it offers a thing called Advisory Messages I’ve decided to use just them.

    What are advisory messages? They are a set of administrative messages that are generated on a specific event, like message consumption, message delivery, topic destruction, and many more. Each type of message is delivered to a separate topic – prefixed with ActiveMQ.Advisory. Since generation of such messages may be an overhead in production systems these features are turned off by default. You need to enable specific type of advisory message for a specific jms destination. You can do this with ths configuration change to activemq.xml

    <destinationPolicy>
       <policyMap>
          <policyEntries>
            <policyEntry queue="my/test/queue" advisoryForDelivery="true" advisoryForConsumed="true"/>                                                   
            <policyEntry topic=">" producerFlowControl="true" memoryLimit="1mb">
              <pendingSubscriberPolicy>
                <vmCursor />
              </pendingSubscriberPolicy>
            </policyEntry>
          </policyEntries>
        </policyMap>
    </destinationPolicy>
    

    As you can see, I’ve specified which advisories I want enabled. The full list of available advisories can be found here.

    Since I wanted to read messages from that topic I’ve added the following configuration to my spring context – there is one destination bean for inserting messages and one bean for advisory topic.

    <bean id="testQueue" class="org.apache.activemq.command.ActiveMQQueue" autowire="constructor">
        <constructor-arg value="my/test/queue" />
    </bean>
    
    <bean id="deliveredToTestQueueAdvisory" class="org.apache.activemq.command.ActiveMQTopic" autowire="constructor">
        <constructor-arg value="ActiveMQ.Advisory.MessageDelivered.Queue.my/test/queue" />
    </bean>
    

    Thanks to this configuration I’ve been able to check that my message was actually delivered to the queue. There’ve been no need to worry about race conditions in consuming the message from original queue – if the X-system read the message, I’d be unable to determine if it has ever been in JMS at all.

    What’s not so nice about that:

    • advisory messages can be thought of as counters rather than debugging information
    • they don’t contain any data that would allow us to match advisory message to the original message – thou you could correlate by timestamp

    All in all, it’s a good tool to have! But perhaps you have some other thoughts on this subject? How do you test JMS?

You May Also Like

Thought static method can’t be easy to mock, stub nor track? Wrong!

No matter why, no matter is it a good idea. Sometimes one just wants to check or it's necessary to be done. Mock a static method, woot? Impossibru!

In pure Java world it is still a struggle. But Groovy allows you to do that really simple. Well, not groovy alone, but with a great support of Spock.

Lets move on straight to the example. To catch some context we have an abstract for the example needs. A marketing project with a set of offers. One to many.

import spock.lang.Specification

class OfferFacadeSpec extends Specification {

    OfferFacade facade = new OfferFacade()

    def setup() {
        GroovyMock(Project, global: true)
    }

    def 'delegates an add offer call to the domain with proper params'() {
        given:
            Map params = [projId: projectId, name: offerName]

        when:
            Offer returnedOffer = facade.add(params)

        then:
            1 * Project.addOffer(projectId, _) >> { projId, offer -> offer }
            returnedOffer.name == params.name

        where:
            projectId | offerName
            1         | 'an Offer'
            15        | 'whasup!?'
            123       | 'doskonała oferta - kup teraz!'
    }
}
So we test a facade responsible for handling "add offer to the project" call triggered  somewhere in a GUI.
We want to ensure that static method Project.addOffer(long, Offer) will receive correct params when java.util.Map with user form input comes to the facade.add(params).
This is unit test, so how Project.addOffer() works is out of scope. Thus we want to stub it.

The most important is a GroovyMock(Project, global: true) statement.
What it does is modifing Project class to behave like a Spock's mock. 
GroovyMock() itself is a method inherited from SpecificationThe global flag is necessary to enable mocking static methods.
However when one comes to the need of mocking static method, author of Spock Framework advice to consider redesigning of implementation. It's not a bad advice, I must say.

Another important thing are assertions at then: block. First one checks an interaction, if the Project.addOffer() method was called exactly once, with a 1st argument equal to the projectId and some other param (we don't have an object instance yet to assert anything about it).
Right shit operator leads us to the stub which replaces original method implementation by such statement.
As a good stub it does nothing. The original method definition has return type Offer. The stub needs to do the same. So an offer passed as the 2nd argument is just returned.
Thanks to this we can assert about name property if it's equal with the value from params. If no return was designed the name could be checked inside the stub Closure, prefixed with an assert keyword.

Worth of  mentioning is that if you want to track interactions of original static method implementation without replacing it, then you should try using GroovySpy instead of GroovyMock.

Unfortunately static methods declared at Java object can't be treated in such ways. Though regular mocks and whole goodness of Spock can be used to test pure Java code, which is awesome anyway :)No matter why, no matter is it a good idea. Sometimes one just wants to check or it's necessary to be done. Mock a static method, woot? Impossibru!

In pure Java world it is still a struggle. But Groovy allows you to do that really simple. Well, not groovy alone, but with a great support of Spock.

Lets move on straight to the example. To catch some context we have an abstract for the example needs. A marketing project with a set of offers. One to many.

import spock.lang.Specification

class OfferFacadeSpec extends Specification {

    OfferFacade facade = new OfferFacade()

    def setup() {
        GroovyMock(Project, global: true)
    }

    def 'delegates an add offer call to the domain with proper params'() {
        given:
            Map params = [projId: projectId, name: offerName]

        when:
            Offer returnedOffer = facade.add(params)

        then:
            1 * Project.addOffer(projectId, _) >> { projId, offer -> offer }
            returnedOffer.name == params.name

        where:
            projectId | offerName
            1         | 'an Offer'
            15        | 'whasup!?'
            123       | 'doskonała oferta - kup teraz!'
    }
}
So we test a facade responsible for handling "add offer to the project" call triggered  somewhere in a GUI.
We want to ensure that static method Project.addOffer(long, Offer) will receive correct params when java.util.Map with user form input comes to the facade.add(params).
This is unit test, so how Project.addOffer() works is out of scope. Thus we want to stub it.

The most important is a GroovyMock(Project, global: true) statement.
What it does is modifing Project class to behave like a Spock's mock. 
GroovyMock() itself is a method inherited from SpecificationThe global flag is necessary to enable mocking static methods.
However when one comes to the need of mocking static method, author of Spock Framework advice to consider redesigning of implementation. It's not a bad advice, I must say.

Another important thing are assertions at then: block. First one checks an interaction, if the Project.addOffer() method was called exactly once, with a 1st argument equal to the projectId and some other param (we don't have an object instance yet to assert anything about it).
Right shit operator leads us to the stub which replaces original method implementation by such statement.
As a good stub it does nothing. The original method definition has return type Offer. The stub needs to do the same. So an offer passed as the 2nd argument is just returned.
Thanks to this we can assert about name property if it's equal with the value from params. If no return was designed the name could be checked inside the stub Closure, prefixed with an assert keyword.

Worth of  mentioning is that if you want to track interactions of original static method implementation without replacing it, then you should try using GroovySpy instead of GroovyMock.

Unfortunately static methods declared at Java object can't be treated in such ways. Though regular mocks and whole goodness of Spock can be used to test pure Java code, which is awesome anyway :)