messaging-testing-rabbitmq
RabbitMQ integration testing with @SpringRabbitTest, RabbitListenerTestHarness, TestRabbitTemplate, and Testcontainers. Covers Java/Spring, Node.js, and Python. USE WHEN: user mentions "rabbitmq test", "@SpringRabbitTest", "RabbitListenerTestHarness", "TestRabbitTemplate", "RabbitMQContainer", "rabbitmq integration test" DO NOT USE FOR: RabbitMQ configuration - use `rabbitmq` skill; Spring AMQP usage - use `spring-amqp` skill; Generic testcontainers - use `testcontainers` skill
What this skill does
# RabbitMQ Integration Testing
> **Quick References**: See `quick-ref/spring-rabbit-test.md` for @SpringRabbitTest details, `quick-ref/testcontainers-rabbitmq.md` for Testcontainers patterns.
## Testing Approach Selection
| Approach | Speed | Fidelity | Best For |
|----------|-------|----------|----------|
| **@SpringRabbitTest + Harness** | Fast (no broker) | Medium (spy/capture) | Testing listener logic with Spring context |
| **TestRabbitTemplate** | Fast (no broker) | Low (no routing) | Testing send/receive without real broker |
| **Testcontainers RabbitMQContainer** | Slow (~5s startup) | Highest (real broker) | Full integration tests, exchange/queue routing |
**Decision rule**: Use @SpringRabbitTest for unit-testing listeners in Spring context. Use Testcontainers for end-to-end message flow with real routing.
## Java/Spring: @SpringRabbitTest + RabbitListenerTestHarness
### Dependencies
```xml
<dependency>
<groupId>org.springframework.amqp</groupId>
<artifactId>spring-rabbit-test</artifactId>
<scope>test</scope>
</dependency>
```
### Spy Pattern — Verify Listener Called
```java
@SpringBootTest
@SpringRabbitTest
class OrderConsumerSpyTest {
@Autowired
private RabbitListenerTestHarness harness;
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
void shouldInvokeListener() throws Exception {
OrderConsumer spy = harness.getSpy("orderListener");
assertThat(spy).isNotNull();
LatchCountDownAndCallRealMethodAnswer answer =
harness.getLatchAnswerFor("orderListener", 1);
rabbitTemplate.convertAndSend("orders.exchange", "orders.created",
new OrderEvent("123", "CREATED"));
assertThat(answer.await(10)).isTrue();
verify(spy).handleOrder(argThat(e -> e.getOrderId().equals("123")));
}
}
```
### Capture Pattern — Inspect Invocation Data
```java
@SpringBootTest
@SpringRabbitTest
class OrderConsumerCaptureTest {
@Autowired
private RabbitListenerTestHarness harness;
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
void shouldCaptureInvocationData() throws Exception {
rabbitTemplate.convertAndSend("orders.exchange", "orders.created",
new OrderEvent("456", "PAID"));
InvocationData data = harness.getNextInvocationDataFor(
"orderListener", 10, TimeUnit.SECONDS);
assertThat(data).isNotNull();
OrderEvent captured = (OrderEvent) data.getArguments()[0];
assertThat(captured.getOrderId()).isEqualTo("456");
assertThat(captured.getStatus()).isEqualTo("PAID");
}
}
```
### Request-Reply Test
```java
@SpringBootTest
@SpringRabbitTest
class OrderServiceReplyTest {
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
void shouldReturnOrderResponse() {
OrderRequest request = new OrderRequest("item-1", 2);
OrderResponse response = (OrderResponse) rabbitTemplate.convertSendAndReceive(
"orders.exchange", "orders.create", request);
assertThat(response).isNotNull();
assertThat(response.getStatus()).isEqualTo("CREATED");
}
}
```
## Java/Spring: TestRabbitTemplate
For testing without a running broker:
```java
@SpringBootTest
@SpringRabbitTest
class NoBrokerTest {
@Autowired
private TestRabbitTemplate testRabbitTemplate;
@Test
void shouldSendWithoutBroker() {
testRabbitTemplate.convertAndSend("orders.exchange", "orders.created",
new OrderEvent("789", "CREATED"));
// TestRabbitTemplate routes directly to @RabbitListener methods
// Verify side effects (database writes, service calls, etc.)
}
}
```
## Java/Spring: Testcontainers RabbitMQContainer
### With @ServiceConnection (Spring Boot 3.1+)
```java
@SpringBootTest
@Testcontainers
class RabbitIntegrationTest {
@Container
@ServiceConnection
static RabbitMQContainer rabbit = new RabbitMQContainer("rabbitmq:3.13-management");
@Autowired
private RabbitTemplate rabbitTemplate;
@Autowired
private OrderRepository orderRepository;
@Test
void shouldProduceAndConsumeOrder() {
rabbitTemplate.convertAndSend("orders.exchange", "orders.created",
new OrderEvent("123", "CREATED"));
await().atMost(Duration.ofSeconds(10))
.untilAsserted(() -> {
Optional<Order> order = orderRepository.findById("123");
assertThat(order).isPresent();
assertThat(order.get().getStatus()).isEqualTo("CREATED");
});
}
}
```
### Pre-Provisioned Exchanges and Queues
```java
static RabbitMQContainer rabbit = new RabbitMQContainer("rabbitmq:3.13-management")
.withExchange("orders.exchange", "direct")
.withQueue("orders.queue")
.withBinding("orders.exchange", "orders.queue",
Map.of(), "orders.created", "queue");
```
### With @DynamicPropertySource (pre-3.1)
```java
@DynamicPropertySource
static void rabbitProperties(DynamicPropertyRegistry registry) {
registry.add("spring.rabbitmq.host", rabbit::getHost);
registry.add("spring.rabbitmq.port", rabbit::getAmqpPort);
registry.add("spring.rabbitmq.username", rabbit::getAdminUsername);
registry.add("spring.rabbitmq.password", rabbit::getAdminPassword);
}
```
## Node.js: amqplib + Testcontainers
```typescript
import { RabbitMQContainer } from "@testcontainers/rabbitmq";
import amqp from "amqplib";
describe("RabbitMQ Integration", () => {
let container: StartedTestContainer;
let connection: amqp.Connection;
beforeAll(async () => {
container = await new RabbitMQContainer("rabbitmq:3.13-management").start();
connection = await amqp.connect(container.getAmqpUrl());
}, 60_000);
afterAll(async () => {
await connection.close();
await container.stop();
});
it("should produce and consume messages", async () => {
const channel = await connection.createChannel();
const queue = "test-queue";
await channel.assertQueue(queue, { durable: false });
const message = { orderId: "123", status: "CREATED" };
channel.sendToQueue(queue, Buffer.from(JSON.stringify(message)));
const received = await new Promise<any>((resolve) => {
channel.consume(queue, (msg) => {
if (msg) resolve(JSON.parse(msg.content.toString()));
});
});
expect(received.orderId).toBe("123");
await channel.close();
});
});
```
## Python: pika + Testcontainers
```python
import pytest
import pika
import json
from testcontainers.rabbitmq import RabbitMqContainer
@pytest.fixture(scope="module")
def rabbitmq():
with RabbitMqContainer("rabbitmq:3.13-management") as container:
yield container
def test_produce_and_consume(rabbitmq):
params = pika.ConnectionParameters(
host=rabbitmq.get_container_host_ip(),
port=rabbitmq.get_exposed_port(5672),
credentials=pika.PlainCredentials("guest", "guest"),
)
connection = pika.BlockingConnection(params)
channel = connection.channel()
channel.queue_declare(queue="test-queue")
message = {"orderId": "123", "status": "CREATED"}
channel.basic_publish(exchange="", routing_key="test-queue",
body=json.dumps(message))
method, props, body = channel.basic_get(queue="test-queue", auto_ack=True)
assert method is not None
assert json.loads(body)["orderId"] == "123"
connection.close()
```
## Anti-Patterns
| Anti-Pattern | Problem | Solution |
|--------------|---------|----------|
| Not using `@SpringRabbitTest` | Manual harness setup | Annotation auto-configures harness and template |
| Ignoring `InvocationData` timeout | Flaky or hanging tests | Always pass timeout to `getNextInvocationDataFor()` |
| Hardcoded exchange/queue names in tests | Coupling to production config | Use constants or test-specific names |
| No `await()` for async consumers | Assertions run before consumption | Use Awaitility or CountDownLatch |
| StarRelated in Backend & APIs
jfrog
IncludedInteract with the JFrog Platform via the JFrog CLI and REST/GraphQL APIs. Use this skill when the user wants to manage Artifactory repositories, upload or download artifacts, manage builds, configure permissions, manage users and groups, work with access tokens, configure JFrog CLI servers, search artifacts, manage properties, set up replication, manage JFrog Projects, run security audits or scans, look up CVE details, query exposures scan results from JFrog Advanced Security, manage release bundles and lifecycle operations, aggregate or export platform data, or perform any JFrog Platform administration task. Also use when the user mentions jf, jfrog, artifactory, xray, distribution, evidence, apptrust, onemodel, graphql, workers, mission control, curation, advanced security, exposures, or any JFrog product name.
cupynumeric-migration-readiness
IncludedPre-migration readiness assessor for porting NumPy to cuPyNumeric. Use BEFORE substantial porting work begins when the user asks whether code will scale on GPU, whether they should migrate to cuPyNumeric, which NumPy patterns transfer cleanly, what must be refactored before porting, or mentions pre-port assessment, scaling analysis, or refactor planning. Inspect the user's source code, look up NumPy usage, cross-reference the cuPyNumeric API support manifest, and distinguish distributed-scaling-friendly patterns from blockers such as unsupported APIs, scalar synchronization, host round-trips, Python/object-heavy control flow, shape/data-dependent branching, and in-place mutation hazards. Produce a verdict of READY, LIGHT REFACTOR, SIGNIFICANT REFACTOR, or NOT RECOMMENDED, with concrete refactor pointers.
alibabacloud-data-agent-skill
IncludedInvoke Alibaba Cloud Apsara Data Agent for Analytics via CLI to perform natural language-driven data analysis on enterprise databases. Data Agent for Analytics is an intelligent data analysis agent developed by Alibaba Cloud Database team for enterprise users. It automatically completes requirement analysis, data understanding, analysis insights, and report generation based on natural language descriptions. This tool supports: discovering data resources (instances/databases/tables) managed in DMS, initiating query or deep analysis sessions, real-time progress tracking, and retrieving analysis conclusions and generated reports. Use this Skill when users need to query databases, analyze data trends, generate data reports, ask questions in natural language, or mention "Data Agent", "data analysis", "database query", "SQL analysis", "data insights".
token-optimizer
IncludedReduce OpenClaw token usage and API costs through smart model routing, heartbeat optimization, budget tracking, and native 2026.2.15 features (session pruning, bootstrap size limits, cache TTL alignment). Use when token costs are high, API rate limits are being hit, or hosting multiple agents at scale. The 4 executable scripts (context_optimizer, model_router, heartbeat_optimizer, token_tracker) are local-only — no network requests, no subprocess calls, no system modifications. Reference files (PROVIDERS.md, config-patches.json) document optional multi-provider strategies that require external API keys and network access if you choose to use them. See SECURITY.md for full breakdown.
resend-cli
IncludedUse this skill when the task is specifically about operating Resend from an AI agent, terminal session, or CI job via the official resend CLI: installing/authenticating the CLI, sending/listing/updating/cancelling emails, batch sends, domains and DNS, webhooks and local listeners, inbound receiving, contacts, topics, segments, broadcasts, templates, API keys, profiles, or debugging Resend CLI/API failures. Trigger on mentions of Resend CLI, `resend`, `resend doctor`, `resend emails send`, `resend domains`, `resend webhooks listen`, `resend emails receiving`, or agent-friendly terminal automation.
alibabacloud-odps-maxframe-coding
IncludedUse this skill for MaxFrame SDK development and documentation navigation on Alibaba Cloud MaxCompute (ODPS). Helps answer MaxFrame API, concept, official example, and supported pandas API questions; create data processing programs; read/write MaxCompute tables; debug jobs (remote or local); and build custom DPE runtime images. Trigger when users mention MaxFrame, MaxCompute with MaxFrame, ODPS table processing, DPE runtime, MaxFrame docs/examples, DataFrame/Tensor operations, or GPU runtime setup. Works for both English and Chinese queries about Alibaba Cloud data processing with MaxFrame.