tushu/tests/basic_test.cpp

116 lines
2.8 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <cassert>
#include <iostream>
#include <string>
#include "app.hpp"
/// @brief 测试图书管理系统核心功能
/// 使用标准库 assert不依赖第三方测试框架。
static void testAddAndFind() {
std::cout << "[Test] testAddAndFind ... ";
App app;
assert(app.size() == 0);
Book b1{"书名A", "作者A", "ISBN-001"};
assert(app.addBook(b1));
assert(app.size() == 1);
// 重复 ISBN 应返回 false
Book b2{"书名B", "作者B", "ISBN-001"};
assert(!app.addBook(b2));
assert(app.size() == 1);
const Book* found = app.findByIsbn("ISBN-001");
assert(found != nullptr);
assert(found->getTitle() == "书名A");
assert(found->getAuthor() == "作者A");
// 不存在的 ISBN
assert(app.findByIsbn("ISBN-999") == nullptr);
std::cout << "PASSED\n";
}
/// @brief 测试删除功能
static void testRemove() {
std::cout << "[Test] testRemove ... ";
App app;
app.addBook(Book{"A", "a", "X"});
app.addBook(Book{"B", "b", "Y"});
assert(app.size() == 2);
// 删除存在的
assert(app.removeBook("X"));
assert(app.size() == 1);
// 删除不存在的
assert(!app.removeBook("Z"));
assert(app.size() == 1);
std::cout << "PASSED\n";
}
/// @brief 测试搜索功能(不区分大小写)
static void testSearch() {
std::cout << "[Test] testSearch ... ";
App app;
app.addBook(Book{"C++ Primer", "Stanley Lippman", "I1"});
app.addBook(Book{"Effective Modern C++", "Scott Meyers", "I2"});
app.addBook(Book{"设计模式", "GoF", "I3"});
// 按书名搜索(不区分大小写)
auto r1 = app.search("c++");
assert(r1.size() == 2);
// 按作者搜索
auto r2 = app.search("stanley");
assert(r2.size() == 1);
assert(r2[0].getIsbn() == "I1");
// 无匹配
auto r3 = app.search("不存在的书");
assert(r3.empty());
std::cout << "PASSED\n";
}
/// @brief 测试借出和归还
static void testBorrowReturn() {
std::cout << "[Test] testBorrowReturn ... ";
App app;
app.addBook(Book{"A", "a", "I-A"});
// 借出
assert(app.borrowBook("I-A"));
const Book* b = app.findByIsbn("I-A");
assert(b != nullptr);
assert(b->isBorrowed());
// 重复借出应失败
assert(!app.borrowBook("I-A"));
// 归还
assert(app.returnBook("I-A"));
assert(!b->isBorrowed());
// 重复归还应失败
assert(!app.returnBook("I-A"));
// 不存在的 ISBN
assert(!app.borrowBook("I-NONE"));
assert(!app.returnBook("I-NONE"));
std::cout << "PASSED\n";
}
/// @brief 主测试入口
int main() {
std::cout << "===== 图书管理系统单元测试 =====\n\n";
testAddAndFind();
testRemove();
testSearch();
testBorrowReturn();
std::cout << "\n✅ 所有测试通过!\n";
return 0;
}