HiveMQ Community Edition in a test container
Written by Yannick Weber
Category: HiveMQ Testing Test Container MQTT Client
Published: March 17, 2020
Testing your MQTT client application with a HiveMQ Community Edition test container
Testing your MQTT client application is not a simple task, since you have to have a running MQTT broker in your testing environment. Sharing your broker deployment between multiple tests can lead to unwanted interferences, unexpected behaviour and flaky tests. The solution is to start a containerized HiveMQ broker that you use exclusively for each test and destroy afterwards. This blog post shows you how to do this automatically in JUnit 4 and JUnit 5 with the help of the Testcontainers Project. If you are new to MQTT protocol, I recommend you to read MQTT Essentials here.
JUnit 4
First, add the following dependencies to your classpath:
Next, add this class that extends the JUnit 4 TestWatcher
to your testing environment:
|
|
You can use the @Rule
annotation to add the HiveMQTestContainerRule
to every JUnit 4 test class that you want.
The MQTT port can be retrieved with the getMqttPort
method.
|
|
JUnit 5
First, add the following dependencies to your classpath:
Next, add this class that implements the JUnit5 BeforeEachCallback
and AfterEachCallback
to your testing environment:
|
|
You can use the @RegisterExtension
annotation to add the HiveMQTestContainerExtension
to every JUnit 5 test class as desired.
The MQTT port can be retrieved with the getMqttPort
method.
|
|
Conclusion
These methods make it very easy to automate the process of starting a fresh MQTT broker. The development and testing process for your client applications becomes more robust when you use use a containerized, isolated, and exclusive broker for every test. You can find the code for the JUnit 4 and JUnit5 example over at GitHub.
About Yannick Weber
Yannick is a Senior Software Engineer and one of the core members of HiveMQ’s product development team. He is focusing on quality development of HiveMQ’s many tools and extensions. In addition, he is the maintainer of the HiveMQ module in the testcontainers-java project.
Contact Yannick