Generate Mock Services with a Single Sentence Using AI – No More Hand‑Written Fake Data

The article shows how AI‑powered "smart mock" decorators let developers describe a scenario in natural language and instantly obtain realistic JSON responses with optional latency, eliminating the need to write hundreds of lines of mock data or maintain separate mock servers.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Generate Mock Services with a Single Sentence Using AI – No More Hand‑Written Fake Data

Problem

When backend APIs are not ready or third‑party services are too expensive to call during development, frontend work stalls. Traditional mocking requires writing extensive JSON stubs and maintaining a separate mock server, which adds significant maintenance overhead.

Smart Mock concept

Smart Mock replaces manual JSON creation with a large language model (LLM). Developers describe the desired scenario in natural language; the LLM generates a standards‑compliant JSON response and can optionally inject simulated network latency.

Implementation

import json
from openai import OpenAI

# Initialize AI client
client = OpenAI(api_key="your_key")

def smart_mock(scenario, latency=0):
    """scenario: natural‑language description, e.g. "user balance insufficient"
    latency: simulated network delay in seconds"""
    def decorator(func):
        def wrapper(*args, **kwargs):
            # 1. Ask AI to generate mock data
            prompt = f"""You are a senior backend developer. Based on the scenario '<{scenario}>', generate a standard JSON response. Include code, message, data fields. Use appropriate HTTP status codes for error scenarios. Make the data look realistic. Return only the JSON string."""
            response = client.chat.completions.create(
                model="gpt-4o",
                messages=[{"role": "user", "content": prompt}]
            )
            mock_json_str = response.choices[0].message.content
            # 2. Optional latency
            if latency > 0:
                import time
                print(f"⏳ Simulating network latency {latency} seconds…")
                time.sleep(latency)
            print(f"🤖 AI‑generated mock data: {mock_json_str}")
            return json.loads(mock_json_str)
        return wrapper
    return decorator

# --- Test cases ---
@smart_mock("支付系统正在维护中,返回503错误")
def pay_order():
    pass

@smart_mock("查询天气成功,北京晴天,25度")
def get_weather():
    pass

print(pay_order())
print(get_weather())

Example output

{
  "code": 503,
  "message": "Service Unavailable: 支付网关正在维护",
  "data": null,
  "retry_after": 3600
}

The generated JSON includes context‑specific fields such as retry_after, demonstrating the model's understanding of HTTP semantics.

Key features

Scenario description serves as documentation; no separate API spec lookup is required.

Developers write no JSON manually; the LLM produces the payload at runtime.

Optional latency argument (e.g., @smart_mock("支付成功", latency=5)) pauses execution, enabling testing of loading spinners or timeout handling.

The decorator can generate error responses with appropriate status codes and additional fields (e.g., retry_after for 503).

By prompting the AI for “dirty” or malformed data, testers can cover edge cases such as garbled third‑party responses or unknown error codes.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PythonAILLMAutomated TestingDecoratorMock Testing
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.