Grey-Box Testing for Microservices: Using Internal Knowledge Without Source Code Access

Grey-Box Testing for Microservices: Using Internal Knowledge Without Source Code Access

Grey-box testing occupies the middle ground between black-box (no knowledge of internals) and white-box (full source code access). You know enough about the internals to design better tests without examining every line of code.

In microservices architectures, grey-box testing is often the only practical approach for testing service integrations. You usually don't have source access to every service, but you do have access to database schemas, API contracts, message format specifications, and infrastructure configurations.

What Grey-Box Knowledge Is Available

For a typical microservice, external testers have access to:

API contracts: OpenAPI/Swagger specifications define endpoints, request/response schemas, error codes, authentication requirements.

Database schemas: even without source code, you often have access to the schema migrations or live database schema. The schema reveals data structures, constraints, relationships, and indexes.

Message schemas: event-driven architectures have message schemas (Avro, protobuf, JSON Schema) that define message structure and field types.

Infrastructure configuration: Kubernetes manifests, Terraform configurations, and environment variable definitions reveal service dependencies, resource limits, and configuration parameters.

Logs and metrics: even in production, logs reveal internal decision paths, error conditions, and performance characteristics.

Documentation: architectural decision records (ADRs), service runbooks, and data flow diagrams.

This knowledge, combined with external API testing, produces grey-box tests that are significantly more effective than pure black-box tests.

Using Database Schema Knowledge

The database schema is the most revealing internal artifact for test design.

Deriving constraints from schema

A schema like:

CREATE TABLE orders (
    id          BIGINT PRIMARY KEY,
    user_id     BIGINT NOT NULL REFERENCES users(id),
    status      VARCHAR(20) NOT NULL CHECK (status IN ('PENDING', 'CONFIRMED', 'SHIPPED', 'DELIVERED', 'CANCELLED')),
    total       DECIMAL(10, 2) NOT NULL CHECK (total >= 0),
    created_at  TIMESTAMP NOT NULL DEFAULT NOW(),
    shipped_at  TIMESTAMP,
    delivered_at TIMESTAMP,
    INDEX idx_user_id (user_id),
    INDEX idx_status (status)
);

This schema reveals test cases you'd need to discover through black-box testing:

  • total is DECIMAL(10, 2): test values near 99999999.99 and 100000000.00 (exceeds precision)
  • total >= 0: test negative values (should reject)
  • status has exact allowed values: test "REFUNDED" (not in enum)
  • user_id is NOT NULL: test create order without user (should reject)
  • user_id references users: test with non-existent user_id (should reject)
  • shipped_at is nullable: test queries that depend on shipped_at being null (unshipped orders)

Black-box testing would require discovering all these constraints through trial and error. Schema knowledge provides them upfront.

Identifying race conditions from schema

Schema indexes and constraints hint at concurrency risks:

ALTER TABLE inventory ADD UNIQUE (product_id, warehouse_id);

This unique constraint suggests: two simultaneous creates for the same product+warehouse will cause a conflict. Test concurrent creation:

  1. Two requests simultaneously try to create inventory for product 123 in warehouse A
  2. Both read "no inventory exists"
  3. Both attempt INSERT
  4. One succeeds; one gets UNIQUE constraint violation

The schema tells you this race condition exists. Test it explicitly.

Testing referential integrity through the API

For the orders table with user_id REFERENCES users(id):

Test the cascading behavior:

  1. Create a user
  2. Create an order for that user
  3. Attempt to delete the user
  4. Expected: either delete fails (RESTRICT) or order is cascade-deleted

The schema doesn't specify which FK action — but the test reveals what actually happens. If the API deletes the user and returns 200 but the order still exists with a dangling user_id, that's a data integrity bug.

Using OpenAPI Specifications

The API specification is richer than it appears for test design purposes.

Schema-based partition derivation

An OpenAPI schema:

PostOrderRequest:
  type: object
  required: [user_id, items, shipping_address]
  properties:
    user_id:
      type: integer
      minimum: 1
    items:
      type: array
      minItems: 1
      maxItems: 50
      items:
        $ref: '#/components/schemas/OrderItem'
    shipping_address:
      $ref: '#/components/schemas/Address'
    discount_code:
      type: string
      maxLength: 20
      nullable: true

From the spec:

  • user_id minimum: 1: test 0 and -1 as invalid values
  • items minItems: 1: test empty array
  • items maxItems: 50: test 50 items (valid) and 51 (invalid)
  • discount_code nullable: true: test with null, with empty string, with 21-char code
  • shipping_address required: test without it

These are the same tests BVA/EP would generate from requirements — but the spec provides the exact boundary values without ambiguity.

Error response testing from spec

responses:
  '400':
    description: Invalid request
    content:
      application/json:
        schema:
          $ref: '#/components/schemas/ErrorResponse'
  '409':
    description: Order already exists for this idempotency key
  '422':
    description: Business rule violation

The spec documents which error codes the service should return. Test each explicitly:

  • 400: send malformed JSON, missing required fields
  • 409: send same request twice with idempotency key
  • 422: send valid request that violates business rules (invalid discount code, insufficient stock)

A service that returns 500 instead of 400 for invalid input, or 400 instead of 409 for duplicate requests, is not meeting its contract.

Message Format Testing for Event-Driven Services

For services that publish events (Kafka, SQS, EventBridge), message schemas define what test cases to design.

Avro/Protobuf schema-based testing

For a published event:

{
  "type": "record",
  "name": "OrderCreated",
  "fields": [
    {"name": "orderId", "type": "string"},
    {"name": "userId", "type": "long"},
    {"name": "totalAmount", "type": {"type": "bytes", "logicalType": "decimal", "precision": 10, "scale": 2}},
    {"name": "items", "type": {"type": "array", "items": "OrderItem"}},
    {"name": "createdAt", "type": {"type": "long", "logicalType": "timestamp-millis"}}
  ]
}

Tests derived from schema knowledge:

  • totalAmount is decimal with precision 10, scale 2: verify event has correct precision (not floating point)
  • createdAt is timestamp-millis: verify milliseconds since epoch (not seconds, not ISO string)
  • items is an array: verify empty array vs. non-empty array are both published
  • Field presence: all fields present in published event (no optional fields omitted)

Publish a known order and consume the event. Verify the event structure matches the schema exactly.

Schema evolution testing

When message schemas evolve, backward/forward compatibility must be maintained:

  • Add an optional field: consumers that don't know the field should still process the message
  • Remove a field: consumers that expected the field must handle its absence
  • Change a type: this breaks compatibility

Grey-box schema knowledge lets you test schema evolution without guessing what consumers expect.

Infrastructure Knowledge as Test Input

Infrastructure configuration reveals deployment constraints and resource limits that black-box tests miss.

Resource limit testing

From a Kubernetes pod spec:

resources:
  requests:
    memory: "256Mi"
    cpu: "100m"
  limits:
    memory: "512Mi"
    cpu: "500m"

The 512Mi memory limit tells you: if a request causes the service to allocate more than 512MB, it will be OOM-killed. Test large payloads or bulk operations that might approach this limit.

livenessProbe:
  httpGet:
    path: /health
    port: 8080
  initialDelaySeconds: 30
  periodSeconds: 10
  failureThreshold: 3

Liveness probe configuration tells you: the pod is killed if /health fails 3 times in a row (30 seconds). Test that a service under high load or database connection issues doesn't fail health checks incorrectly.

Environment variable and configuration testing

From infrastructure config:

env:
  - name: MAX_CONNECTIONS
    value: "100"
  - name: REQUEST_TIMEOUT_MS
    value: "5000"
  - name: FEATURE_NEW_CHECKOUT
    value: "true"

Configuration-derived tests:

  • Test behavior at exactly 100 concurrent connections (boundary)
  • Test requests that exceed 5000ms (timeout handling)
  • Verify feature flag behavior (new checkout is enabled for all users)

Log Pattern Analysis

Production logs reveal code paths and conditions that aren't visible from the API. Reading logs is grey-box knowledge.

Identifying untested code paths

If you see log patterns like:

2026-05-30 WARN  order.service - Fallback payment processor used for user 12345
2026-05-30 ERROR order.service - Inventory check timeout, proceeding without stock validation

These log patterns indicate code paths that are executing in production but may not have explicit tests:

  • The fallback payment processor path
  • The inventory timeout fallback path

These become test cases: intentionally trigger the timeout condition (or disable inventory service) and verify the fallback behavior is correct.

Error frequency analysis

# Analyze error patterns from logs
grep "ERROR" service.log | 
  sed 's/.*ERROR  //' | 
  sort | uniq -c | sort -rn | head 20

The most frequent error patterns that aren't caught by current tests are exactly the gaps you should fill.

Combining Grey-Box with Black-Box Tests

Grey-box testing doesn't replace black-box testing — it informs and extends it.

Start with black-box tests: test the API from the outside, without any internal knowledge. This ensures the external interface works.

Add grey-box tests: use schema, contract, and infrastructure knowledge to add tests for:

  • Database constraint boundaries
  • Message format edge cases
  • Resource limit conditions
  • Error paths visible only in logs

Verify with white-box (when available): if you have access to source code, verify that your grey-box test cases achieve meaningful code coverage.

Summary

Grey-box testing for microservices turns partial internal knowledge into concrete test cases. Database schemas reveal constraints and partitions. API specifications define error codes and input boundaries. Message schemas define event structure and evolution requirements. Infrastructure configuration defines resource limits and timeouts.

The approach: gather all available grey-box artifacts before writing tests. Systematically extract test cases from each artifact. Add these to your black-box test suite.

The result: test cases that would take weeks of exploratory testing to discover through pure black-box methods — derived in hours from artifacts you already have access to.

Start now free