Use this prompt when you need to generate a comprehensive test suite for API endpoints that accept or return polymorphic payloads defined with OpenAPI's oneOf/anyOf constructs and discriminator properties. This prompt is designed for integration test engineers and SDETs who must verify that an API correctly routes requests to the right variant, rejects invalid combinations, and returns proper error responses when discriminator values are missing, wrong, or ambiguous. The prompt assumes you have an OpenAPI specification snippet containing the polymorphic schema definition, including the discriminator property name, mapping table, and all variant schemas. It produces structured test cases with request payloads, expected status codes, expected response bodies, and validation assertions ready for automation frameworks.
Prompt
OneOf/AnyOf Discriminator Test Prompt Template

When to Use This Prompt
Defines the ideal scenario, required inputs, and boundaries for generating discriminator-based polymorphic API tests.
The ideal input is a self-contained OpenAPI fragment that defines a discriminator object with its propertyName and mapping fields, along with the complete schemas for each variant referenced in the mapping. The prompt works best when variant schemas are distinct enough to produce meaningful routing differences—if variants differ only by optional fields, the test value diminishes. You should also provide any relevant endpoint context (method, path, success status codes) so the generated tests include realistic request routing. For high-risk domains like payments or identity where incorrect variant routing has security or financial implications, always include [RISK_LEVEL] as high to trigger additional negative test cases and human review markers in the output.
Do not use this prompt for simple enum validation, flat schema conformance, or non-discriminated union types; those require different test design strategies. This prompt is also not suitable for generating performance tests, fuzz tests, or authentication/authorization tests—it focuses exclusively on structural polymorphic routing correctness. If your API uses implicit polymorphism (guessing the variant from field shapes without a discriminator property), this prompt will not produce reliable tests; you need a schema shape matching approach instead. After generating the test suite, always validate that the discriminator values in the generated test payloads match the mapping table exactly, and run at least one positive and one negative case manually before integrating into CI.
Use Case Fit
Where the OneOf/AnyOf Discriminator Test Prompt Template delivers value and where it introduces risk. Use these cards to decide if this prompt fits your current API testing workflow.
Strong Fit: Polymorphic Endpoint Validation
Use when: Your API accepts or returns payloads with oneOf/anyOf schemas where the discriminator property determines the variant. Guardrail: Provide the full schema definition and discriminator mapping in [CONTEXT] so the model can generate tests that verify correct variant routing for each possible value.
Strong Fit: Invalid Discriminator Rejection Testing
Use when: You need to verify that the API rejects requests with missing, misspelled, or invalid discriminator values. Guardrail: Include expected HTTP status codes and error response schemas in [CONSTRAINTS] so generated tests assert the correct rejection behavior, not just any 4xx response.
Poor Fit: Simple Enum or Fixed Schema Endpoints
Avoid when: Your endpoint uses a flat schema with no polymorphic branching. Risk: The prompt will over-generate discriminator test cases that don't apply, wasting execution time and creating false coverage signals. Guardrail: Use a standard schema conformance prompt instead for non-polymorphic endpoints.
Required Input: Complete Discriminator Mapping
Risk: Without the full discriminator-to-schema mapping, the model may hallucinate variant schemas or miss edge cases. Guardrail: Always include the discriminator.mapping object from your OpenAPI spec in [CONTEXT]. If the mapping uses implicit conventions, document those explicitly before running the prompt.
Operational Risk: Schema Drift Between Spec and Implementation
Risk: The prompt generates tests from the spec, but the running API may have diverged. Tests will pass against the spec but fail against reality, or worse, miss implementation-only variants. Guardrail: Pair this prompt with a contract compatibility check that diffs the spec against actual response samples before trusting generated tests.
Operational Risk: Combinatorial Explosion in anyOf
Risk: anyOf schemas with multiple valid combinations can produce an unmanageable number of test cases. Guardrail: Set explicit [CONSTRAINTS] on maximum test case count and prioritize boundary combinations (all valid, none valid, exactly one valid) over exhaustive enumeration.
Copy-Ready Prompt Template
A copy-ready prompt that generates a comprehensive test suite for validating OneOf/AnyOf discriminator logic in your API schema.
This prompt template is designed to be pasted directly into your AI harness. It instructs the model to act as a specialized API test engineer, generating a structured test suite from your polymorphic schema definition. The prompt uses square-bracket placeholders for all dynamic inputs, ensuring you can adapt it to any OpenAPI specification, GraphQL schema, or custom contract that uses discriminators for variant selection.
textYou are a senior API test engineer specializing in polymorphic schema validation. Your task is to generate a comprehensive test suite for the OneOf/AnyOf discriminator logic defined in the provided schema. # SCHEMA DEFINITION [SCHEMA_DEFINITION] # OUTPUT SCHEMA You must output a single JSON object with the following structure: { "test_suite_name": "string", "discriminator_property": "string", "test_cases": [ { "test_id": "string", "test_name": "string", "category": "positive_variant_routing | negative_invalid_discriminator | negative_missing_discriminator | negative_invalid_combination | edge_case", "description": "string", "input_payload": {}, "expected_status_code": 200 | 400 | 422 | 500, "expected_variant_routed_to": "string | null", "expected_error_message_contains": "string | null", "risk_level": "low | medium | high" } ], "coverage_summary": { "total_variants": "number", "variants_tested": "number", "untested_variants": ["string"], "discriminator_values_tested": ["string"] } } # CONSTRAINTS [CONSTRAINTS] # EXAMPLES [EXAMPLES] # INSTRUCTIONS 1. Parse the SCHEMA_DEFINITION to identify the discriminator property and all possible variant mappings. 2. For each variant, generate a positive test case that sends a valid payload with the correct discriminator value and variant-specific fields. 3. Generate negative test cases for: an invalid discriminator value, a missing discriminator property, and a payload that mixes fields from multiple variants. 4. Include edge cases such as empty objects, null discriminator values, and extra unexpected properties. 5. Ensure the output strictly conforms to the OUTPUT SCHEMA. Do not include any text outside the JSON object.
To adapt this template, replace [SCHEMA_DEFINITION] with the raw JSON or YAML of your OpenAPI schema component, focusing on the oneOf or anyOf block and its discriminator mapping. The [CONSTRAINTS] placeholder should be filled with any specific rules, such as 'Do not test deprecated variants' or 'Only generate tests for the Pet schema'. Use the [EXAMPLES] placeholder to provide one or two correct input-output pairs, which dramatically improves the model's adherence to your exact output schema and test-naming conventions. For high-risk financial or healthcare APIs, ensure a human reviews the generated input_payload objects before execution to prevent accidental data corruption.
After pasting the prompt, validate the model's output against the defined JSON schema before feeding test cases into your automation framework. A common failure mode is the model generating a discriminator_property that doesn't match the schema's actual propertyName. Always run a quick diff check. The next section, 'Implementation Harness', will show you how to wire this prompt into an automated pipeline with retry logic and schema validation.
Prompt Variables
Each placeholder must be replaced before the prompt is sent to the model. Validation notes help catch common mistakes.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[OPENAPI_SPEC] | The raw OpenAPI specification containing oneOf/anyOf discriminator definitions | openapi: 3.0.3 components: schemas: Pet: discriminator: propertyName: petType | Must be valid YAML or JSON. Parse check: deserialize with an OpenAPI parser before prompt assembly. Reject if no discriminator property found in any schema. |
[DISCRIMINATOR_SCHEMA_NAME] | The specific schema name within the spec that contains the discriminator to test | Pet | Must match a schema name present in [OPENAPI_SPEC]. Schema check: confirm schema exists and contains a discriminator object. Reject if schema is missing or has no discriminator. |
[DISCRIMINATOR_PROPERTY] | The property name used to distinguish between variant schemas | petType | Must match the propertyName value in the discriminator object. Schema check: extract from spec programmatically. Reject if property does not appear in all mapping target schemas. |
[MAPPING_TABLE] | The discriminator mapping object linking property values to schema references | Cat: '#/components/schemas/Cat' Dog: '#/components/schemas/Dog' | Must be a valid JSON or YAML mapping. Schema check: every referenced schema must resolve within [OPENAPI_SPEC]. Reject if any $ref target is missing or circular. |
[VARIANT_SCHEMAS] | The resolved schema definitions for each variant in the mapping table | Cat: {properties: {hunts: boolean}} Dog: {properties: {breed: string}} | Must include all schemas referenced in [MAPPING_TABLE]. Schema check: resolve all $refs before prompt assembly. Reject if any variant schema is empty or has no distinct properties. |
[OUTPUT_FORMAT] | The desired output structure for generated test cases | json | Must be one of: json, yaml, csv. Format check: validate against allowed enum. Default to json if unspecified. Reject if format is unsupported by downstream test harness. |
[TEST_FRAMEWORK] | Target test framework for generated test code | pytest | Must be a supported framework identifier. Framework check: confirm framework adapter exists in harness. Reject if framework requires dependencies not available in test environment. |
[INCLUDE_NEGATIVE_TESTS] | Whether to generate test cases for invalid discriminator values and missing properties | Must be true or false. Boolean check: coerce string values. Default to true for safety. Reject if value is ambiguous or non-boolean. |
Implementation Harness Notes
How to wire the discriminator test prompt into a production test generation pipeline with validation, retries, and schema-aware output checks.
The OneOf/AnyOf Discriminator Test Prompt Template is designed to be called programmatically, not used as a one-off chat interaction. In a production harness, you feed it a JSON Schema or OpenAPI schema fragment containing oneOf/anyOf with discriminator mappings, and it returns a structured test suite. The harness must validate that the output contains the expected test case fields: discriminatorProperty, mappingCoverage (all variants tested), validVariantTests, invalidCombinationTests, and errorExpectationTests. Without this validation, you risk shipping test suites that miss unmapped variants or fail to verify that the API rejects invalid discriminator values.
Wire the prompt into a test generation service with the following pipeline: (1) Schema Preprocessing — extract the oneOf/anyOf block and its discriminator definition from the full spec, including the mapping object and each variant's $ref or inline schema. Pass only the relevant fragment to keep context tight. (2) Prompt Execution — call the model with the preprocessed schema as [SCHEMA_FRAGMENT], setting [CONSTRAINTS] to require exhaustive mapping coverage and explicit error test cases. Use a model that supports structured output (JSON mode or function calling) and set response_format to enforce the output schema. (3) Output Validation — before accepting the result, run automated checks: confirm that every key in the discriminator mapping has at least one valid variant test and one invalid combination test; verify that errorExpectationTests cover missing discriminator, unknown discriminator value, and discriminator with mismatched variant shape; check that all test cases include expectedStatusCode and assertions arrays. (4) Retry with Error Feedback — if validation fails, construct a retry prompt that includes the original schema, the partial output, and a specific error message like 'Missing test case for discriminator value "credit_card" in mappingCoverage.' Limit retries to 2 attempts before flagging for human review.
For integration into CI/CD, store the generated test suite as a versioned artifact alongside the schema version it was generated from. When the schema changes, re-run generation and diff the test suites to detect coverage regressions. Avoid running this prompt against entire multi-kilobyte OpenAPI specs without preprocessing — the model will lose precision on discriminator edge cases when context is diluted. If your API uses nested discriminators or polymorphic arrays, split them into separate generation calls and merge the results. For high-risk payment or identity APIs, add a human review step before the generated tests are committed to the test repository, especially for invalidCombinationTests that might expose unintended error-handling gaps.
Expected Output Contract
Validate each generated test case object against this contract before accepting the model output. Reject or repair any object that fails a validation rule.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
testCases | Array of objects | Root must be a JSON array. Reject if not present or not an array. | |
testCases[].id | String (kebab-case) | Must match pattern ^[a-z]+(-[a-z]+)*$. Must be unique within the array. | |
testCases[].discriminatorProperty | String | Must match one of the discriminator property names provided in [SCHEMA_CONTEXT]. | |
testCases[].mappingValue | String or null | Must match a valid mapping value from [SCHEMA_CONTEXT] when variant is 'valid'. Must be null when variant is 'invalid'. | |
testCases[].variant | Enum: ['valid', 'invalid'] | Must be exactly 'valid' or 'invalid'. Reject any other value. | |
testCases[].payload | Object | Must be a valid JSON object. For 'valid' variants, must conform to the subschema identified by the discriminator mapping. For 'invalid' variants, must intentionally violate one constraint. | |
testCases[].expectedStatusCode | Integer | Must be 200 or 201 for 'valid' variants. Must be 400 or 422 for 'invalid' variants. | |
testCases[].expectedRouting | String | Must name the schema variant the payload should route to. For 'invalid' variants, must be the string 'rejection'. |
Common Failure Modes
What breaks first when using the OneOf/AnyOf Discriminator Test Prompt and how to guard against it.
Discriminator Property Omission
What to watch: The model generates test payloads that omit the discriminator property entirely, making it impossible to validate variant routing. This happens when the prompt emphasizes variant properties over the discriminator field itself. Guardrail: Add an explicit pre-generation check instruction that requires the discriminator field to be present in every generated payload before any variant-specific properties are added.
Invalid Discriminator Value Mapping
What to watch: The model invents discriminator values that do not exist in the schema's mapping table, producing test cases that test routing paths the API does not define. This creates false-positive failures and wastes debugging time. Guardrail: Include the full discriminator mapping table in the prompt context and add a post-generation validator that checks every discriminator value against the allowed enum before the test case is accepted.
Variant Property Leakage Across Types
What to watch: The model mixes properties from different variants into a single test payload, creating hybrid objects that are invalid for all defined schemas. This is common when variants share similar field names or the prompt does not enforce strict variant isolation. Guardrail: Add a constraint that each generated test payload must match exactly one variant schema and include a schema conformance check that rejects payloads with properties from multiple variants.
Missing Negative Test Cases for Invalid Combinations
What to watch: The model focuses exclusively on valid variant combinations and fails to generate test cases for invalid discriminator-value pairings, missing critical error-handling coverage. Guardrail: Explicitly require a minimum number of negative test cases that pair valid discriminators with intentionally mismatched variant properties, and include eval criteria that count negative case coverage.
Schema Version Drift in Discriminator Definitions
What to watch: When the API schema evolves and discriminator values or variant schemas change, the prompt continues generating test cases against the old mapping, producing stale tests that no longer match the live API contract. Guardrail: Version-lock the schema reference in the prompt template with a schema hash or version number, and add a pre-execution check that compares the embedded schema version against the current API spec before generating tests.
Overlooking Nested Discriminator Chains
What to watch: The model handles top-level discriminators correctly but misses nested OneOf/AnyOf structures within variant schemas, leaving deeply nested polymorphic branches untested. Guardrail: Add a recursive schema traversal instruction that identifies all discriminator levels in the schema tree and requires test coverage at each nesting depth, with a coverage report that flags untested nested discriminators.
Evaluation Rubric
Score the generated test suite before integrating it into your test repository. Each criterion is rated on a pass/fail basis.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Discriminator Mapping Completeness | Every mappingName in the schema has at least one positive test case | Missing mappingName entries in generated test suite; coverage report shows uncovered discriminator values | Count distinct mappingName values in schema; verify each appears in at least one test case label or payload |
Variant Selection Accuracy | Each positive test case routes to the correct schema variant based on discriminator property value | Test case payload uses discriminator value for variant A but expected response validates against variant B schema | Extract discriminator value from test payload; confirm expected response schema matches the mapping definition for that value |
Invalid Discriminator Rejection | At least one test case per invalid discriminator category: unknown value, missing property, wrong type | No test cases for missing discriminator property or null discriminator value; only happy-path variants tested | Search generated tests for error status codes (400, 422); verify at least one test per invalid category |
OneOf/AnyOf Constraint Enforcement | Test cases validate that exactly one variant matches for OneOf and at least one matches for AnyOf | OneOf test case payload matches multiple variants without triggering error; AnyOf test case rejects valid multi-match payload | Review test assertions for OneOf exclusivity checks and AnyOf inclusivity checks against schema constraint type |
Edge Case Coverage | Boundary tests include: empty object, extra properties, null discriminator, deeply nested variant, all required fields missing | Test suite contains only typical valid and invalid payloads; no boundary or stress inputs present | Scan test payloads for edge patterns: {}, null discriminator, missing required nested fields, unexpected additional properties |
Error Response Validation | Each negative test case asserts correct HTTP status code, error code, and human-readable message presence | Negative test cases only check for non-2xx status without validating error body structure or message field | Inspect test assertions for status code match, error code field existence, and message field non-empty check |
Schema Version Compatibility | Generated tests reference the correct schema version and do not use deprecated discriminator values | Test payloads contain discriminator values removed in the target schema version; assertions check against stale response shapes | Cross-reference discriminator values in test payloads against the schema version changelog; verify no deprecated values used |
Test Independence | Each test case sets up its own state and does not depend on execution order of other tests | Test case assumes resource exists from prior test; fails when run in isolation or randomized order | Execute test cases in reverse order and randomized order; verify all pass independently without shared fixture side effects |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Use the base prompt with a single discriminator schema and a small set of variants. Drop the eval harness and focus on getting correct variant routing for the happy path. Replace [OUTPUT_SCHEMA] with a simple JSON object shape.
codeGenerate test cases for the following discriminator mapping: [DISCRIMINATOR_PROPERTY]: [MAPPING_TABLE] For each variant, produce one valid payload and one invalid payload where the discriminator value does not match the schema.
Watch for
- Missing negative test cases for unmapped discriminator values
- Overly broad instructions that produce generic JSON tests instead of discriminator-specific scenarios
- No validation that the generated payload actually conforms to the variant schema

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us