← 教程列表
coding

Anti-Pattern 6: Mocks Derived from Implementation

📅 2026/6/12 16:30:02⏱ 约 5 分钟阅读👁 8 阅读

**The violation:** ```typescript // Code (BUGGY) calls cleanup() await adapter.cleanup(); // Mock (MATCHES BUG) has cleanup() const mock = { cleanup: vi.fn().mockResolvedValue(undefined) }; // Interface (CORRECT) defines close() interface PlatformAdapter { close(): Promise; } ``` **Why this is wrong:** - Mock encodes the bug into the test - TypeScript can't catch inline mocks with wrong method names - Test passes because both code and mock are wrong - Runtime crashes when real object is used **The fix:** ```typescript // ✅ GOOD: Derive mock from interface // Step 1: Open interface definition (PlatformAdapter) // Step 2: List methods defined there (close, initialize, etc.) // Step 3: Mock EXACTLY those methods const mock = { initialize: vi.fn().mockResolvedValue(undefined), close: vi.fn().mockResolvedValue(undefined), // From interface! }; // Now test FAILS because code calls cleanup() which doesn't exist // That failure reveals the bug BEFORE runtime ```

← 返回教程列表 AI8899 · 内容仅供学习参考