Crafting a Test Case
Learn how to write a test class for RabbitMQ.
We'll cover the following...
With everything in place, it’s time to determine what our system will do. We’re talking about an asynchronous message solution. A simple thing to implement would be receiving a request for a new Item
object at a web controller and forwarding the information as a message through RabbitMQ. A service would be elsewhere, listening for messages. That service could then write the new Item
to MongoDB.
This is a very simple concept we can use over and over. We can also adapt it to our needs. It’s easy to swap out the web controller with something else. Perhaps a message was also transmitted via RabbitMQ. Or, perhaps someone directly invoking the API.
Defining a test class
Let’s return to the initial problem. Namely, a web controller that turns synchronous web requests into asynchronous messages. This time, we’ll choose a test-first approach.
Spring Boot Test, JUnit 5, and Testcontainers put this at our fingertips:
@SpringBootTest //1@AutoConfigureWebTestClient //2@Testcontainers //3@ContextConfiguration //4public class RabbitTest {@Container static RabbitMQContainer container = new RabbitMQContainer(); //5@Autowired WebTestClient webTestClient; //6@Autowired ItemRepository repository; //7@DynamicPropertySource //8static void configure(DynamicPropertyRegistry registry) {registry.add("spring.rabbitmq.host", container::getContainerIpAddress);registry.add("spring.rabbitmq.port", container::getAmqpPort);}...}
Here’s a breakdown of the code above:
-
In line 1, ...