pub struct MockBus {
published: Arc<Mutex<Vec<(String, Vec<u8>)>>>,
senders: Arc<Mutex<HashMap<String, Vec<Sender<Vec<u8>>>>>>,
responders: Arc<Mutex<HashMap<String, Vec<Sender<(Vec<u8>, Sender<Vec<u8>>)>>>>>,
}Expand description
Combined in-memory message bus for unit tests.
Implements Publisher, Subscriber, Requester, and Responder
without a NATS server. Events published via publish() are delivered to any
active subscribe() streams on the same subject, and also recorded so tests
can assert on what was sent via MockBus::published_as. Commands sent via
request() are routed to an active respond() stream on a matching
subject, and the handler’s reply is delivered back to the caller.
Service code that takes impl Publisher + impl Subscriber parameters can be
fully tested without a running NATS server:
use arminius_lib_message_bus::{
Event, Publisher, Subscriber, mock::MockBus,
};
use futures::StreamExt;
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
struct OrderCreated {
order_id: String,
}
impl Event for OrderCreated {
const SUBJECT: &str = "OrderCreated.v1";
}
async fn handle_order(publisher: &impl Publisher, order_id: &str) {
publisher
.publish(OrderCreated { order_id: order_id.to_string() })
.await
.unwrap();
}
let bus = MockBus::new();
handle_order(&bus, "order-42").await;
let published = bus.published_as::<OrderCreated>();
assert_eq!(published[0].order_id, "order-42");Fields§
§published: Arc<Mutex<Vec<(String, Vec<u8>)>>>All published messages, recorded so tests can assert on what was sent.
senders: Arc<Mutex<HashMap<String, Vec<Sender<Vec<u8>>>>>>Active subscriber senders, keyed by subscribed subject pattern.
responders: Arc<Mutex<HashMap<String, Vec<Sender<(Vec<u8>, Sender<Vec<u8>>)>>>>>Active responder senders, keyed by the subject pattern they handle.