AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

Generating Unit Tests and Mocking Dependencies in Legacy Code with Code GPT in VS Code

傅星達 · 365Finds Editorial
Indexed 88,650 Wiki articles

Put 365 Wiki to work with your AI

Copy the prompt below, paste it into the AI you already use, then ask your question.

Download full Skill

Try it with the prompt first. If you use 365 Wiki often, install the full 365Wiki Skill so you do not have to paste it again. No regular AI? Gemini or Microsoft Copilot on the web will work.

365Wiki Skill

Software engineers tackling legacy codebases without automated tests face a recurring dilemma: modifying complex, tightly coupled business functions without a safety net risks production regressions, yet manually writing test harnesses and mocking external dependencies from scratch can take days. Inside Visual Studio Code, Code GPT accelerates this process from hours of manual stubbing to an automated, guided workflow. However, 365Finds finds that relying on the naive right-click context menu generates brittle tests that hallucinate signatures. To reliably test legacy systems, teams must pair frontier reasoning models via BYOK or Code GPT Pro with Agent Mode and granular context mentions (#file, @codebase), enabling Code GPT to inspect real dependency contracts, scaffold mocking harnesses, and verify test execution in the terminal.


The Reality of Legacy Code and Why Zero-Shot AI Fails

Michael Feathers famously defined legacy code as code without tests. In practice, legacy systems are rarely structured for testing:

When an engineer simply highlights a 200-line legacy function and runs a zero-shot test command, standard LLMs generate tests against idealized, decoupled code. The resulting test files frequently attempt to mock modules that do not exist, use incorrect method names, or omit necessary setup fixtures.


Prerequisites & Workspace Setup in VS Code

To make Code GPT effective across legacy architectures, configure your IDE workspace correctly before generating tests:

  1. Install the Extension: Install DanielSanMedium.dscodegpt from the VS Code Marketplace.
  2. Model Selection: Legacy test generation requires high-tier reasoning to trace complex control flows and nested mocks. 365Finds strongly advises using frontier models (such as Claude 3.5 Sonnet or GPT-4o) via Bring Your Own Key (BYOK) or a Code GPT Pro subscription ($10/month). Lightweight economy models struggle with complex mocking contracts and frequently produce test isolation bugs.
  3. Switch Profile to Agent Mode: In the Code GPT chat panel, switch the profile dropdown from Chat Mode or Search Mode to Agent Mode. Agent Mode grants Code GPT access to internal tools (Read File, Create File, Edit File, and Run Terminal Command), which turns Code GPT from a passive code generator into an active testing agent that creates test files and executes the test runner.
  4. Augment Codebase Context: Click the augmented context icon to index the project. Create a .codegptignore file at your workspace root to exclude node_modules, dist, build, and log directories. This ensures the indexing engine focuses on actual source files and shared type definitions.

Step-by-Step Workflow: Generating Tests and Mocking Dependencies

Step 1: Pin Dependency Signatures Using Context Mentions

Never isolate the legacy function completely from its environment. Open the Code GPT Chat panel in Agent Mode, locate the dependencies instantiated or invoked inside the target function, and attach them using # mentions or the + Add Context button:

Providing these reference files prevents Code GPT from guessing method names and response schemas.

Step 2: Highlight Code and Issue the Constrained Prompt

Highlight the target legacy function in the editor. While you can right-click and select CodeGPT: Unit Test CodeGPT, writing a structured prompt in the chat panel with the /Unit Test command yields significantly higher fidelity:

/Unit Test
Target: Selected function in #orderProcessor.js
Framework: Jest with TypeScript
Dependencies to mock:
- Database query client from #pool.js: Mock `query` method to return fixtures without touching real DB.
- External payment API from #paymentGateway.js: Mock `chargeCustomer` using `jest.spyOn` or `jest.mock`.

Requirements:
1. Isolate all network and disk I/O.
2. Cover three distinct branches:
   - Happy path: Successful transaction and state persistence.
   - Handled failure: Payment declined (verify transaction rollback is called).
   - Unhandled exception: Database timeout (verify error propagation and logging).
3. Include `beforeEach` and `afterEach` hooks to reset all mock calls.

Step 3: Scaffold Mocks Across Popular Frameworks

Depending on your tech stack, Code GPT adapts the mocking strategy to legacy idioms:

Stack & FrameworkMocking MechanismKey Prompting Constraint for Code GPT
Node.js / TypeScript (Jest)jest.mock(), jest.spyOn()Instruct Code GPT to mock at the module boundary and call jest.clearAllMocks() in afterEach.
Python (Pytest)unittest.mock.patch, monkeypatchDirect Code GPT to patch the dependency where it is imported, not where it is defined.
Go (Go test)Interface extraction, testify/mockAsk Code GPT to generate a minimal seam/interface wrapper around hardcoded structs if no interface exists.

Step 4: Autonomous Execution and Self-Correction (Agent Mode)

In Agent Mode, Code GPT leverages its internal tools to complete the engineering loop:

  1. Tool Create File: Writes the generated test suite directly into tests/orderProcessor.test.ts.
  2. Tool Run Terminal Command: Executes the project's test command (e.g., npx jest tests/orderProcessor.test.ts or pytest tests/test_order_processor.py).
  3. Self-Correction: If the test fails due to a missing mock return value, unhandled promise rejection, or syntax mismatch, Code GPT inspects the terminal stderr output, uses Edit File to adjust the mock fixtures, and re-runs the test until green.

Overcoming Legacy Anti-Patterns

When dealing with decades-old code, automated test generation hits architectural roadblocks. 365Finds recommends two tactical interventions:

1. Hardcoded Instantiations (new Dependency())

If legacy code contains const db = new DatabaseConnection() inside the function body, traditional module mocks can become awkward.

2. Mock Pollution Across Large Suites

Legacy tests often bleed state. Ensure your prompt explicitly instructs Code GPT to restore mocked singletons, clear timer mocks (jest.useRealTimers()), and delete temporary test environment variables in teardown blocks.


Strategic Comparison: Workflow Approaches

DimensionDefault Context Menu (Unit Test CodeGPT)Prompt-Driven Agent Mode with Context Mentions
Dependency ContextZero-shot; guesses external class methodsExact; reads imported module APIs via #file tags
Mock AccuracyHigh risk of hallucinated method namesHigh fidelity; matches real signatures and return types
Execution LoopManual copy-paste and manual terminal debuggingAutonomous; writes files and executes test runner via CLI tools
Best Suited ForPure algorithmic utilities, leaf string helpersComplex business services, legacy ORM logic, API controllers
Model RecommendationEconomy models sufficientFrontier models (Claude 3.5 Sonnet / GPT-4o) strongly recommended

The 365Finds Verdict

Code GPT in VS Code is one of the most effective tools for dismantling legacy code debt, but only when treated as an orchestration partner rather than a magic wand.


References