AD SPACE AVAILABLE · BRAND PARTNERS WELCOME

How Software Engineers Use Sourcegraph Cody Codebase Context to Generate Unit Tests, Mocks, and Edge-Case Test Suites

Dan Budington · 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

Every senior backend engineer knows the acute frustration of asking a generic AI assistant to write unit tests for an enterprise service. You feed it a 50-line business method, and it spits back syntactically valid code that fails immediately upon execution. The AI invents fake database fixtures, mocks third-party clients using deprecated libraries, assumes constructors take parameters that were deprecated two quarters ago, and tests trivial happy paths while ignoring concurrent race conditions. Spending twenty minutes fixing a hallucinated mock harness is noticeably slower than hand-crafting the tests yourself.

The problem has never been the underlying large language model’s grasp of syntax. The problem is total blindness to the rest of the repository.

Sourcegraph Cody takes an entirely different architectural path. By routing queries through Sourcegraph's native search engine and its structural Code Graph, Cody treats test generation not as a creative writing prompt, but as a graph traversal and dependency resolution challenge. At 365Finds, we evaluate developer tools based on whether they eliminate high-friction cognitive drag; Sourcegraph Cody is one of the rare assistants that genuinely understands how an organization's internal test conventions, mock factories, and domain entities fit together across multiple files.


The Code Graph Advantage: Beyond Open-File Context

Standard AI code completion plugins operate strictly within a localized scope: the open buffer, recently visited tabs, and a shallow vector search over immediate files. In a production monorepo or layered microservice, that scope is disastrously inadequate. A single business logic function typically depends on:

Sourcegraph Cody resolves this through a three-tier context retrieval pipeline:

flowchart TD
    A[Cursor on Unit Under Test] --> B[Cody Context Fetching Engine]
    B --> C[Keyword Search: Local file tokens]
    B --> D[Sourcegraph Search API: Repo-wide symbols & AST]
    B --> E[Code Graph: Injected Interfaces & Sibling Tests]
    C --> F[Augmented Prompt Context]
    D --> F
    E --> F
    F --> G[Underlying LLM: Claude 3.5 Sonnet / GPT-4o]
    G --> H[Idiomatic Unit Tests + Accurate Mocks + Edge Cases]

When you trigger a test command in Sourcegraph Cody, it does not merely look at the selected lines. It analyzes the abstract syntax tree (AST) to identify dependent types and injected interfaces. It then queries the Sourcegraph index to retrieve real implementations, existing mock conventions, and sibling test suites. The prompt injected into the LLM contains your actual project patterns rather than generic training-set boilerplate.


Step 1: Grounding Cody with Precise @-mention Context

While Cody's automated index retrieval handles broad workspace discovery, generating rock-solid mocks requires deliberate steering. At 365Finds, our engineers recommend explicitly pinning the test harness using Cody’s @-mention syntax rather than relying purely on zero-shot inference.

In your IDE chat or inline edit prompt, provide the exact anchor points of your testing infrastructure:

@user_service.go @user_repository.go @mocks/mock_user_repository.go
Generate comprehensive unit tests for UserService.UpdateUserEmail. 
Follow our existing table-driven test style in @user_service_test.go. 
Use the existing mock generator pattern from @mocks/mock_user_repository.go.

By supplying:

  1. The implementation file (@user_service.go)
  2. The dependency interface (@user_repository.go)
  3. The existing mock double (@mocks/mock_user_repository.go)
  4. An existing sibling test (@user_service_test.go)

Sourcegraph Cody immediately aligns its output with your repository's exact assertion syntax, variable naming schemes, and mock expectation setups.


Step 2: Synthesizing Mocks Without Hallucinating APIs

Consider a real-world scenario: a payment processing method in Go that depends on an external payment gateway, a distributed cache, and an event publisher.

A generic AI assistant routinely hallucinates mock methods: it guesses that the cache has a method called cache.Set(key, val), when your company’s internal wrapper actually requires cache.SetWithTTL(ctx, key, val, ttl, tags...). The resulting test code won't even compile.

Because Sourcegraph Cody indexes the symbol graph across the codebase, it extracts the exact signatures of the injected interfaces:

// Extracted interface context indexed by Cody Code Graph
type PaymentGateway interface {
    Authorize(ctx context.Context, req *AuthorizationRequest) (*AuthorizationResult, error)
    Capture(ctx context.Context, transactionID string, amount int64) (*CaptureResult, error)
}

type EventPublisher interface {
    Publish(ctx context.Context, topic string, payload []byte) error
}

When instructed to mock these interfaces, Cody queries your repository for existing mock generation patterns. If your repository uses uber-go/mock (formerly golang/mock), Cody builds expectations using EXPECT().Authorize(...). If your team prefers hand-written test doubles, it constructs a fake struct implementing the exact interface signature.

Here is an example of Cody's contextual mock setup adhering to team conventions:

func TestProcessPayment_Success(t *testing.T) {
    ctrl := gomock.NewController(t)
    defer ctrl.Finish()

    mockGateway := mocks.NewMockPaymentGateway(ctrl)
    mockPublisher := mocks.NewMockEventPublisher(ctrl)

    ctx := context.Background()
    expectedTxID := "tx_test_987654"

    mockGateway.EXPECT().
        Authorize(gomock.Any(), gomock.Eq(&AuthorizationRequest{
            CustomerID: "cust_123",
            AmountCents: 5000,
            Currency:    "USD",
        })).
        Return(&AuthorizationResult{
            Status:        AuthStatusApproved,
            TransactionID: expectedTxID,
        }, nil).
        Times(1)

    mockPublisher.EXPECT().
        Publish(gomock.Any(), "payments.authorized", gomock.Any()).
        Return(nil).
        Times(1)

    service := NewPaymentService(mockGateway, mockPublisher)
    res, err := service.ProcessPayment(ctx, "cust_123", 5000, "USD")

    assert.NoError(t, err)
    assert.Equal(t, expectedTxID, res.TransactionID)
}

Notice the absence of hallucinated parameter types. Because Cody observed AuthStatusApproved and AuthorizationRequest in the project's domain definitions, the enum values and struct fields match the codebase.


Step 3: Driving Edge-Case and Boundary Test Suites

The primary value of unit testing lies not in verifying standard execution paths, but in guarding against edge cases: transient network failures, unexpected empty payloads, token expiration, database timeouts, and context cancellations.

Default test generation commands like /test produce competent baseline tests, but they often gravitate toward trivial positive cases. To generate an exhaustive edge-case suite, 365Finds advises structuring your prompt around a disciplined behavioral matrix.

The Systematic Edge-Case Prompt Recipe

Run the following structured prompt against your target function:

Analyze the error paths, boundary values, and external dependencies of the selected function.
Generate an exhaustive table-driven unit test suite covering:
1. Nil/Null/Empty inputs (empty strings, nil pointers, zero-value IDs).
2. Boundary numeric constraints (negative amounts, MAX_INT overflow, floating-point precision).
3. Dependency failures:
   - External service returns context.DeadlineExceeded (timeout).
   - Downstream service returns HTTP 429 Too Many Requests (rate limiting).
   - Data store returns ErrRecordNotFound vs ErrDatabaseConnectionLost.
4. Concurrency & idempotency:
   - Replay of identical idempotent keys.
5. Assertion integrity:
   - Verify that mocks are called exactly the expected number of times.
   - Assert both the explicit error type and returned error message.

Table-Driven Test Generation Example

Below is the type of production-ready test table Cody produces when fed this contextual prompt:

func TestProcessPayment_EdgeCases(t *testing.T) {
    cases := []struct {
        name          string
        customerID    string
        amount        int64
        currency      string
        mockSetup     func(gw *mocks.MockPaymentGateway, pub *mocks.MockEventPublisher)
        expectedErr   error
        expectedState PaymentState
    }{
        {
            name:       "empty customer ID returns validation error",
            customerID: "",
            amount:     1000,
            currency:   "USD",
            mockSetup:  func(gw *mocks.MockPaymentGateway, pub *mocks.MockEventPublisher) {},
            expectedErr: ErrInvalidCustomer,
            expectedState: StateFailedValidation,
        },
        {
            name:       "zero amount rejected",
            customerID: "cust_valid",
            amount:     0,
            currency:   "USD",
            mockSetup:  func(gw *mocks.MockPaymentGateway, pub *mocks.MockEventPublisher) {},
            expectedErr: ErrInvalidAmount,
            expectedState: StateFailedValidation,
        },
        {
            name:       "gateway timeout bubbles DeadlineExceeded",
            customerID: "cust_valid",
            amount:     2500,
            currency:   "USD",
            mockSetup: func(gw *mocks.MockPaymentGateway, pub *mocks.MockEventPublisher) {
                gw.EXPECT().
                    Authorize(gomock.Any(), gomock.Any()).
                    Return(nil, context.DeadlineExceeded).
                    Times(1)
            },
            expectedErr: context.DeadlineExceeded,
            expectedState: StateFailedUpstream,
        },
        {
            name:       "publisher fails after successful authorization triggers compensation",
            customerID: "cust_valid",
            amount:     2500,
            currency:   "USD",
            mockSetup: func(gw *mocks.MockPaymentGateway, pub *mocks.MockEventPublisher) {
                gw.EXPECT().
                    Authorize(gomock.Any(), gomock.Any()).
                    Return(&AuthorizationResult{TransactionID: "tx_comp_1"}, nil)
                pub.EXPECT().
                    Publish(gomock.Any(), gomock.Any(), gomock.Any()).
                    Return(errors.New("kafka unavailable"))
                gw.EXPECT().
                    Capture(gomock.Any(), "tx_comp_1", int64(0)).
                    Return(nil, nil) // compensating void
            },
            expectedErr: ErrEventPublishFailed,
            expectedState: StateCompensated,
        },
    }

    for _, tc := range cases {
        t.Run(tc.name, func(t *testing.T) {
            ctrl := gomock.NewController(t)
            defer ctrl.Finish()

            gw := mocks.NewMockPaymentGateway(ctrl)
            pub := mocks.NewMockEventPublisher(ctrl)
            tc.mockSetup(gw, pub)

            svc := NewPaymentService(gw, pub)
            res, err := svc.ProcessPayment(context.Background(), tc.customerID, tc.amount, tc.currency)

            if tc.expectedErr != nil {
                assert.ErrorIs(t, err, tc.expectedErr)
            } else {
                assert.NoError(t, err)
            }
            assert.Equal(t, tc.expectedState, res.State)
        })
    }
}

This is not decorative code. It identifies compensatory logic, isolates third-party failure modes, and rigorously checks state machine transitions.


Standardizing Workflows: The Prompt Library and Custom Commands

Relying on individual developers to remember prompt templates leads to uneven test coverage across teams. Sourcegraph Cody addresses this through the Prompt Library and workspace-level custom commands.

Teams can configure reusable, organization-wide test generation commands within .vscode/cody.json or Cody's enterprise Prompt Library:

{
  "commands": {
    "unit-test-suite": {
      "description": "Generate rigorous unit tests matching repo test standards",
      "prompt": "Inspect the selected function and its dependencies. Check existing *_test files in this directory for conventions. Write a complete table-driven test suite using existing mock generators. Cover nil checks, network timeouts, invalid inputs, and error handling. Do not omit assertions or leave TODO placeholders.",
      "context": {
        "code": true,
        "selection": true
      }
    }
  }
}

Once published to your team’s Prompt Library, any developer can highlight a function, run /unit-test-suite, and receive code that strictly enforces the team's engineering standards.


365Finds Institutional Evaluation

Feature / DimensionGeneric LLM AssistantSourcegraph Cody with Code Graph365Finds Assessment
Mock PrecisionGuesses signatures; invents nonexistent methodsIndexes interface definitions; matches real parametersCody eliminates the compilation errors that plague AI mocks.
Project Convention AdherenceDefaults to generic testing librariesDiscovers existing assertion packages and sibling test filesHigh fidelity; seamlessly mirrors team coding style.
Edge-Case ThoroughnessShallow; focuses on happy pathsCapable of multi-state branch analysis when promptedRequires structured prompting, but generates production-ready boundary cases.
Monorepo UsabilityPoor; fails on cross-package referencesNative; traverses dependencies across package boundariesClear organizational advantage for enterprise codebases.

365Finds maintains a clear stance: AI test generation without deep codebase context is counterproductive. It generates tests that pass by accident while giving teams a false sense of test coverage. Sourcegraph Cody succeeds where others fail because its engine is rooted in code graph intelligence rather than conversational guesswork.

When adopting Cody for test generation, establish this non-negotiable protocol across your engineering team: never accept an AI-generated test suite without intentionally flipping an assertion to verify that it fails. A passing test is only as trustworthy as its ability to catch a broken invariant.


References