Restructure code to be more testable by applying dependency injection, interface segregation, and separation of concerns.
Fill in this template
The {{ }} placeholders are variables — drop in your own details, then copy the ready-to-use prompt. (Or copy the template as-is and let your AI assistant fill them in.)
Preview filled prompt
You are a software engineer specializing in test-driven development and testable architecture.
## Code to Refactor
```
{{CODE}}
```
## Test Framework
{{TEST_FRAMEWORK}}
## Instructions
Refactor this code to make it highly testable without changing its external behavior.
### Identify Testability Barriers
First, identify what makes this code hard to test:
1. **Hard-coded dependencies**: Direct imports of concrete implementations
2. **Global state**: Singletons, module-level variables, environment reads
3. **Side effects**: File I/O, network calls, database queries mixed with logic
4. **Temporal coupling**: Code that depends on execution order
5. **Non-determinism**: Date.now(), Math.random(), UUIDs in logic
### Apply Testability Patterns
1. **Dependency Injection**
- Extract dependencies into constructor/function parameters
- Define interfaces for external services
- Create factory functions for default wiring
2. **Pure Core / Imperative Shell**
- Extract pure business logic (no I/O, no side effects)
- Push I/O to the boundaries
- Make the pure core the bulk of the code
3. **Seam Creation**
- Create testable seams at module boundaries
- Use strategy pattern for swappable behavior
- Parameterize things that change
4. **Interface Segregation**
- Define narrow interfaces that tests can easily mock
- Avoid depending on large, broad interfaces
5. **Deterministic Helpers**
- Wrap Date.now(), Math.random() in injectable functions
- Use clock/random abstractions in logic
## Output Format
1. **Testability Assessment**: Score (1-10) with identified barriers
2. **Refactored Code**: The restructured implementation
3. **Interfaces/Types**: New interfaces for dependencies
4. **Factory Function**: Default wiring for production use
5. **Example Tests**: 3-5 tests demonstrating how the refactored code is now easy to test using {{TEST_FRAMEWORK}}
6. **Mock Examples**: Show how to create test doubles for each dependencyTags
Explore more prompts and rules
BeforeMerge offers hundreds of AI prompts, code review rules, guides, and detection patterns to help your team ship better code.