今天測一下昨天寫的redaer事件
先註冊使用者
let mut user = Reader::default();
let service = ReaderService{};
let command = ReaderCommand::CreateReader {
name: "John Smith".to_string(),
};
let events = user.handle(command,&service).await.unwrap();
let event = &events[0];
user.apply(event.clone());
assert_eq!(user.name, "John Smith"); // 正確註冊資訊:姓名
借閱指令
let command = ReaderCommand::BorrowBook {
book_id: "test-book-id".to_string(),
borrowed_date: Utc::now(),
due_date: Utc::now().add(Duration::days(7)),
};
let events = user.handle(command,&service).await.unwrap();
let borrow_event = &events[0];
user.apply(borrow_event.clone());
assert_eq!(user.borrowed_books.len(), 1); // 讀者已借閱1本
assert_eq!(user.borrowed_books[0].book_id, "test-book-id"); // 確認該本 id 正確
再借同樣的書
let command = ReaderCommand::BorrowBook {
book_id: "test-book-id".to_string(),
borrowed_date: Utc::now(),
due_date: Utc::now(),
};
let events = user.handle(command,&service).await;
assert!(events.is_err()); // 確認執行沒有成功
assert_eq!(events.unwrap_err().0, "讀者已借出同一本書"); // 提示正確錯誤訊息
把書借滿
const MAX_BOOKS_PER_READER: usize = 5;
for i in 1..MAX_BOOKS_PER_READER {
let command = ReaderCommand::BorrowBook {
book_id: format!("test-book-id-{}", i + 1),
borrowed_date: Utc::now(),
due_date: Utc::now(),
};
let events = user.handle(command,&service).await.unwrap();
let event = &events[0];
user.apply(event.clone());
}
assert_eq!(user.borrowed_books.len(), MAX_BOOKS_PER_READER);
借滿後想再進行借閱操作
let command = ReaderCommand::BorrowBook {
book_id: "test-book-id-6".to_string(),
borrowed_date: Utc::now(),
due_date: Utc::now(),
};
let events = user.handle(command,&service).await;
assert!(events.is_err());
assert_eq!(events.unwrap_err().0, "讀者最多只能借 5 本書");
執行還書操作
let command = ReaderCommand::ReturnBook {
book_id: "test-book-id".to_string(),
return_date: Utc::now(),
};
let events = user.handle(command,&service).await.unwrap();
let return_event = &events[0];
user.apply(return_event.clone());
assert_eq!(user.borrowed_books.len(), 4); // 借閱剩4本
assert_eq!(user.borrowed_history.len(), 1); // 歷史紀錄增加1筆
assert_eq!(user.borrowed_history[0].book_id, "test-book-id"); // 確認歷史紀錄正確
rollback 還書事件,回到前一狀態
user.rollback(return_event.clone());
assert_eq!(user.borrowed_books.len(), 5);
assert_eq!(user.borrowed_history.len(), 0);
rollback 借書事件,回到前一狀態
user.rollback(borrow_event.clone());
assert_eq!(user.borrowed_books.len(), 4);
assert_eq!(user.borrowed_history.len(), 0);