AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

How to Use GitHub Copilot to Write Unit Tests for Legacy 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

Legacy code is terrifying not because it is old, but because it works in production for reasons nobody alive can fully explain.

When you inherit an un-tested, eight-hundred-line method riddled with nested conditionals, static database singletons, and magic numbers, the natural instinct is avoidance. The second instinct, nowadays, is to highlight the entire mess in your IDE, fire up GitHub Copilot Chat, hit /tests, and hope artificial intelligence bails you out.

At 365Finds, we strongly warn against that second instinct.

Doing a blind test generation with GitHub Copilot on legacy code is one of the fastest ways to introduce a false sense of security into a software organization. Copilot is an obliging collaborator. If you hand it an undocumented spaghetti function that silently swallows a NullPointerException and returns -1, a naive prompt will cause Copilot to write a test asserting that returning -1 on null is the intended architectural design. It cements production bugs into concrete unit test contracts.

Yet, ignoring GitHub Copilot when facing legacy systems is equally foolish. Writing test harnesses for tightly coupled, untested code by hand is soul-crushing, slow, and mechanically repetitive.

Here is 365Finds' field guide on how to actually deploy GitHub Copilot to construct unit tests for legacy codebases—without letting the model fool you.


1. Pinning Reality First: Characterization Over "Correctness"

In Michael Feathers' seminal work Working Effectively with Legacy Code, legacy code is defined bluntly: code without tests. When tackling such code, your immediate objective is never to write "good" tests that verify what the code should do according to some imagined specification. Your job is to write characterization tests (or pinning tests) that document what the code actually does right now.

Copilot defaults to being helpful, which means it often tries to "clean up" or infer proper business logic. You must explicitly break this habit in your prompts.

Instead of running /tests blindly, anchor your request in Copilot Chat with strict behavioral boundaries:

@workspace #file:BillingEngine.cs
Generate characterization tests for the ProcessMonthlyInvoice method using xUnit and Moq.
Strict constraints:
1. Capture current runtime behavior as-is, including odd return codes, suppressed exceptions, and side effects.
2. Do not attempt to fix or refactor any logic you deem buggy.
3. If negative balances return an empty string instead of an error, assert an empty string.

At 365Finds, we find that forcing Copilot into a "characterization" mindset cuts out 80% of its tendency to invent idealized, polite assertions that fail the moment you run them against legacy binaries.


2. The Two-Step Prompt: Catalog Branches Before Generating Code

One of the worst traps developers fall into is asking Copilot to spit out code on turn one. Large language models struggle when asked to simultaneously trace deeply nested execution graphs and scaffold verbose mocking boilerplate in a single generation window.

Separate the diagnosis from the code emission.

Step A: Extract the Execution Matrix

Select the legacy function and ask Copilot to map the decision space first:

"Analyze the selected legacy function. List every conditional branch, edge case, boundary value, and potential unhandled state. Identify hidden side effects and external static calls. Do not write test code yet."

Review this breakdown. Copilot is remarkably sharp at spotting subtle branches—like an obscure if (tier == 3 && country != "US") hidden fifty lines deep. If Copilot missed an environmental flag or a thread-local variable, point it out in the chat before moving forward.

Step B: Generate Tests Against the Approved Matrix

Once you confirm the scenario inventory:

"Now, generate isolated unit tests for scenarios 1 through 4 from your list above. Use NSubstitute for mock dependencies."

Chunking your legacy testing into three or four branches per prompt keeps Copilot inside its high-accuracy context window and prevents truncated test files.


3. Finding "Seams" and Mocking Coupled Dependencies

Legacy code is hostile to unit testing because it rarely uses dependency injection. You will almost certainly encounter direct calls like DatabaseConnection.GetInstance(), DateTime.Now, or disk I/O buried deep inside business computations.

When Copilot encounters these, it will often hallucinate mock frameworks that cannot physically intercept static methods in your runtime, leaving you with code that fails to compile.

365Finds recommends using Copilot to design the minimal viable "seam"—the Michael Feathers term for a place where you can alter behavior without editing existing code.

Ask Copilot:

This method relies on static call ConfigurationManager.AppSettings["TaxRate"]. 
Suggest the smallest, non-breaking refactoring to introduce a testable seam without altering the public API consumed by existing callers.

Copilot will usually suggest extracting an internal virtual method or wrapping the static access behind an overloaded constructor that defaults to the static implementation. Once the seam exists, you can prompt Copilot to write the mocks against the seam.


4. Standardize Frameworks with Workspace Instructions

If your legacy repository was built in 2016, modern defaults will break it. Copilot might happily generate modern fluent assertions, modern record types, or contemporary testing libraries that your legacy build pipeline cannot compile.

Lock Copilot's memory using repository-level instructions. Create a .github/copilot-instructions.md file in your repository root:

# Testing Legacy Modules
- Testing framework: JUnit 4 (do NOT use JUnit 5 or Jupiter annotations).
- Mocking framework: Mockito 2.x using standard syntax; do not use Mockito 5 inline static mocks.
- Test naming convention: MethodName_StateUnderTest_ExpectedBehavior.
- Target Java version: Java 8 compatibility only.

Copilot Chat and inline completions read this context automatically. At 365Finds, adding a twenty-line instruction file eliminated nearly all compiler friction caused by version hallucinations.


5. The Verification Protocol: Intentional Mutation

Here is an uncomfortable truth: Copilot will occasionally write unit tests with assertions that pass regardless of what the underlying code actually does, or tests where assertions check mocked return values rather than actual logic.

At 365Finds, we enforce a mandatory rule: Never trust a green characterization test generated by an AI until you have seen it fail.

Use the following verification loop:

  1. Run the Copilot-generated test suite. It must pass against your legacy code.
  2. Go into the legacy source code and intentionally introduce a subtle bug—change an operator from >= to >, or delete a line updating a status flag.
  3. Re-run the test.
  4. If the test still passes, that test is hollow theater. Throw it away or ask Copilot: "I modified line 42 to skip status updates, but test UpdateOrder_ValidData_SetsStatus still passed. Rewrite the test assertion to strictly verify that state change."
  5. Revert your deliberate bug and ensure the suite is green again.

Summary of the 365Finds Legacy Testing Workflow

StageCopilot RoleHuman Developer Responsibility
Branch AnalysisScans code paths and enumerates edge casesValidates hidden domain constraints and config flags
Seam InsertionSuggests minimal-risk refactoring wrappersVerifies zero breakage for external production callers
Test GenerationScaffolds tedious assertions and mock fixturesStrictly specifies characterization instead of fixes
ValidationDiagnoses test failures via /fixTestFailureMutates code manually to confirm assertions are real

Copilot cuts down the mechanical friction of legacy characterization tests by roughly 70%. But it is an accelerator, not an auditor. Use it to write the scaffolding; keep your own hand firmly on the safety catch.

References