测试使用数据库的代码很具有挑战性——您需要真实的数据行为,而不会产生不稳定性或缓慢。方法包括测试数据库、内存数据库、事务/回滚和模拟数据层——各有利弊。
挑战
Database-interacting code needs testing, but databases bring challenges:
→ real DB → realistic but SLOWER; needs SETUP and CLEANUP (state between tests)
→ shared state → tests can interfere (order dependence, flakiness)
→ mocking the DB → fast but may not catch real query/integration bugs
→ Choose an approach balancing realism, speed, and isolation.
