An interface test code generation system based on domain model

The interface test code generation system based on domain models automatically generates interface test cases and test data with business semantics, solving the problems of low test case value, difficult link orchestration, and high change and maintenance costs in existing technologies, and achieving high coverage and strong controllability of interface test automation.

CN122450834APending Publication Date: 2026-07-24BEIJING XINLUHANG TECHNOLOGY CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
BEIJING XINLUHANG TECHNOLOGY CO LTD
Filing Date
2026-05-06
Publication Date
2026-07-24

AI Technical Summary

Technical Problem

Existing interface testing technologies struggle to incorporate business semantics, generate low-value test cases, face difficulties in link orchestration, incur high change and maintenance costs, and exhibit weak controllability of test data.

Method used

The domain model-based interface test code generation system automatically generates interface test cases, test data, and executable test project code with business semantics through a domain model management module, an interface contract parsing module, a domain-interface mapping module, a test case generation module, a test data generation module, an assertion generation module, and a code generation module.

Benefits of technology

It achieves highly covered, maintainable, and incrementally updatable interface testing automation, improving the value of test cases and the controllability of test data, and reducing change and maintenance costs.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122450834A_ABST
    Figure CN122450834A_ABST
Patent Text Reader

Abstract

The application belongs to the technical field of domain models, and particularly relates to an interface test code generation system based on a domain model, which comprises a domain model management module, an interface contract analysis module, a domain-interface mapping module, a test case generation module, a test data generation module, an assertion generation module, a code generation module, an execution and feedback module. The application generates test cases and assertions by using domain rules, invariants and state machines, covers business correctness instead of only interface availability, improves the value of test cases, maps domain behaviors into multiple interface calling sequences, automatically generates pre-step, dependency graph and cleaning strategy, solves the problem of link arrangement difficulty, generates multiple types of test data according to domain constraints, is controllable and reproducible, realizes incremental update by comparing models and contract versions, reduces change maintenance cost, supports multi-language / cross-framework reuse, and reuses unified domain semantic assets.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of domain model technology, and in particular to an interface test code generation system based on a domain model. Background Technology

[0002] With the increasing popularity of microservice architectures, open platforms, and front-end / back-end separation, the number of HTTP / REST / RPC interfaces provided by systems continues to grow. Automated interface testing has become a crucial means of ensuring delivery quality and regression efficiency. Existing technologies typically construct interface tests using the following methods: Generate or scaffolding based on interface contracts (such as OpenAPI / Swagger, Postman collections): can generate request samples or call SDKs, but often only cover shallow semantics such as field types and required field validation, and are difficult to express business rules, invariants, state transitions and cross-interface chain dependencies.

[0003] Based on recording and playback or traffic playback: Request samples can be obtained quickly, but the controllability of test data is weak, it is difficult to systematically generate boundary / exception / combination test cases, and the maintenance cost is high when the interface changes, the authentication strategy changes, or the environment is different.

[0004] Manually written automated tests offer strong coverage but heavily rely on test engineering experience. The code is scattered, has poor reusability, and is difficult to maintain in sync with the evolution of business rules.

[0005] Therefore, existing technologies generally suffer from problems such as "low use case value, difficulty in link orchestration, assertions lacking business semantics, and high cost of change and maintenance," and there is an urgent need for a technical solution that can introduce business semantics and automatically generate high-quality interface test code. Summary of the Invention

[0006] This invention aims to provide an interface test code generation system based on a domain model. The system introduces a computable and versionable domain model (domain entities, constraint rules, invariants, state machines, domain behaviors / use cases, etc.) and establishes a mapping relationship with the interface contract, thereby automatically generating interface test cases, test data, assertions and executable test project code with business semantics, achieving high coverage, maintainability and incremental updateability of interface testing automation.

[0007] To achieve the above objectives, the present invention adopts the following technical solution: An interface test code generation system based on a domain model is provided. The system includes a domain model management module, an interface contract parsing module, a domain-interface mapping module, a test case generation module, a test data generation module, an assertion generation module, a code generation module, and an execution and feedback module. The functions of each module are as follows: Domain Model Management Module: Used to create, import, and edit domain models, perform syntax and consistency checks, and manage model versions; Interface contract parsing module: used to parse OpenAPI / Swagger / Postman or custom interface descriptions and generate unified interface metadata; Domain-Interface Mapping Module: Used to establish the mapping relationship between domain objects / behaviors / state transitions and interfaces, forming a mapping table and mapping rules; Test case generation module: Generates forward, backward, boundary, composite, state transition, and link test cases based on the domain model and mapping rules, and generates a test case dependency graph; Test data generation module: Generates test data based on domain constraints and strategies, including pre-existing data, abnormal data, boundary data, and reproducible random data; Assertion generation module: Generates field assertions, rule assertions, and cross-interface consistency assertions based on domain rules, invariants, and mapping relationships; Code generation module: Outputs execution interface test project code based on a template engine; Execution and Feedback Module: Executes the generated test project, outputs coverage and failure information, and feeds it back into the model and generation strategy to optimize subsequent generation.

[0008] Preferably, the domain model includes: Domain entities: users, orders, accounts, including attributes and relationships between entities; Attribute constraints: type, length, value range, enumeration, regular expression, uniqueness, NOT NULL, cross-field constraints; Domain rules and invariants: Describe business constraints using execution expressions, rule engine syntax, or DSL; State machine: Defines a set of states and transition relationships, with each transition carrying a triggering condition and an action; Domain behaviors / use cases: create, pay, cancel, query, etc., and define inputs, outputs, preconditions and post-effects.

[0009] Coverage objectives and strategies: full state transition coverage, critical path coverage, error code coverage, and boundary coverage.

[0010] Preferably, the domain model is expressed in JSON / YAML / DSLw file format or a graph model, and supports versioning management.

[0011] Preferably, the domain-interface mapping module includes: Mapping of entity attributes to request / response fields: Supports bidirectional mapping between business object attributes and interface fields, including path expression parsing and type conversion rules; Mapping of domain behaviors to interface sets: One domain behavior corresponds to one or more interfaces; Mapping state transitions to interface call sequences: binding state machine transitions to the sequence of executed interface steps and verification steps; Mapping from rules / invariants to assertion templates: Mapping domain rules to the execution of assertion expressions and assertion endpoints.

[0012] Preferably, the mapping relationship is obtained through manual configuration, semi-automatic derivation, or extraction from code annotations / domain service descriptions.

[0013] Preferably, the test case generation module includes the following steps: S1: Read the domain model version Vd and the interface contract version Va, and complete the model and contract parsing, verification and normalization; S2: Construct a mapping graph Gmap, where nodes contain entities / attributes / rules / states / behaviors / interfaces, representing mappings and dependencies; S3: Generate test paths according to coverage strategy: If a state machine exists, generate a set of state transition paths; if a behavior chain exists, generate a behavior dependency sequence. S4: Generate interface steps for each path: including pre-steps, action steps, and verification steps; S5: Convert paths and steps into use case descriptions and output them to the code generator.

[0014] Preferably, the test data generation module includes: Positive data: When all constraints and preconditions are met, the expected business behavior and state transition are triggered; Reverse data: selective constraint violation, used for abnormal paths and error code overriding; Boundary data: minimum / maximum value, empty string, extremely long string, special characters, date thresholds, empty / full sets, etc., used for boundary coverage; Reproducibility and isolation: Supports random seed, environment variable injection, tenant / account pool isolation, data cleanup and rollback strategies.

[0015] Preferably, the assertion generation module includes: Field assertions: response status code, error code, existence of fields that must be returned, field type and range validation; Rule assertions: Convert domain rules / invariants into execution assertion expressions; Cross-interface consistency assertions: consistency after creation, consistency after modification, consistency during state transition, read-write consistency, and idempotency verification; Timing / Concurrency Assertions: Based on domain idempotency rules, verify the consistency of results for duplicate requests, the handling of concurrent conflicts, and the effectiveness of retries.

[0016] Preferably, the code generation module includes: Interface client encapsulation: Unified handling of authentication, signature, retries, timeouts, logging and tracking IDs, and consistency with the interface contract; Data factories and fixtures: encapsulate forward / reverse / boundary data construction, and support dependency data creation and cleanup; Assertion library: Implements field assertions, rule assertions, and cross-interface consistency assertions to improve reusability and maintainability; Test case code: Organize test classes and test case methods according to domain behavior or state machine path to form a runnable test suite; Configuration and Reporting: Generate environment configuration files, test report output, and statistical data on test case coverage and business rule coverage.

[0017] The beneficial effects of this invention are as follows: The domain model-based interface test code generation system of the present invention utilizes domain rules, invariants and state machines to generate test cases and assertions, covering business correctness rather than just interface availability, thereby enhancing the value of test cases; The domain model-based interface test code generation system of the present invention maps domain behavior into multiple interface call sequences, automatically generates pre-steps, dependency graphs and cleanup strategies, solves the problem of link orchestration difficulties, and generates various types of test data according to domain constraints, which is highly controllable and reproducible. The domain model-based interface test code generation system of the present invention achieves incremental updates by comparing the model with the contract version, reducing change and maintenance costs, and supports multi-language / cross-framework reuse, reusing unified domain semantic assets. Attached Figure Description

[0018] Figure 1 This is a system architecture block diagram of an interface test code generation system based on a domain model proposed in this invention; Figure 2 This is a flowchart of the overall process of an interface test code generation system based on a domain model proposed in this invention. Figure 3 This is a schematic diagram of the domain model for an interface test code generation system based on a domain model proposed in this invention. Figure 4 This is a schematic diagram of the domain interface mapping of an interface test code generation system based on a domain model proposed in this invention; Figure 5 This invention presents a use case dependency graph for an interface test code generation system based on a domain model. Figure 6This is a schematic diagram illustrating assertion generation for an interface test code generation system based on a domain model proposed in this invention. Detailed Implementation

[0019] The technical solutions of the present invention will be clearly and completely described below with reference to the accompanying drawings of the embodiments of the present invention. Obviously, the described embodiments are only some embodiments of the present invention, and not all embodiments.

[0020] Reference Figures 1-6 Example 1: Implementation of Interface Test Code Generation Based on E-commerce Order Domain. This example targets the order business scenario of an e-commerce platform. It fully utilizes the domain model-driven characteristics of this system to achieve automated generation of test code for order-related interfaces. The specific implementation process is as follows: In the domain model management module, technical personnel create order domain models and complete versioned storage. The domain entity is defined as Order{ id: String, userId: String, amount: Decimal, status: Enum, items: Array}, where OrderItem contains attributes such as productId, quantity, and unitPrice. The relationship between entities is clearly defined as Order and OrderItem having an inclusion relationship, with one Order corresponding to multiple OrderItems.

[0021] The attribute constraints are set as follows: amount > 0, items array length ≥ 1, status enumeration value is {CREATED, PAID, SHIPPED, DELIVERED, CANCELED}, userId is not empty and conforms to the UUID format, and OrderItem quantity ≥ 1 and unitPrice > 0. Domain rules and invariants are described using DSL language, including "order payment amount cannot exceed the user's current available balance," "cancelled orders cannot be paid for," and "order status cannot be reverted to unpaid status after shipment."

[0022] The state machine defines the state transition paths: CREATED→PAID (triggering behavior: PayOrder), PAID→SHIPPED (triggering behavior: ShipOrder), SHIPPED→DELIVERED (triggering behavior: DeliverOrder), CREATED→CANCELED (triggering behavior: CancelOrder). The triggering condition for each transition includes permission verification (e.g., only the order creator can cancel the order), and the action includes updating the order status timestamp.

[0023] The domain behaviors include CreateOrder, PayOrder, CancelOrder, ShipOrder, DeliverOrder, and QueryOrder. The input for CreateOrder is userId and item information, the precondition is that the user is logged in, and the post-effect is to generate an Order entity and assign a unique ID. The input for PayOrder is orderId and payment method, the precondition is that the order status is CREATED and the user has sufficient balance, and the post-effect is to update the order status to PAID.

[0024] The coverage objectives and strategies are set as follows: full coverage of state transitions, coverage of key business paths (creation-payment-delivery-receipt), coverage of core error codes (insufficient balance, order not found, invalid status), and coverage of amount and quantity boundaries. This domain model is stored in YAML format and is marked with version number V1.0.

[0025] The interface contract parsing module connects to the OpenAPI contract file provided by the e-commerce platform and parses out the metadata of 6 core interfaces: POST / api / v1 / orders (create order), the request parameters include userId, items (productId, quantity, unitPrice), and the response includes orderId, status, and createTime; POST / api / v1 / orders / {orderId} / pay (payment order), the path parameter is orderId, the request parameters include paymentMethod and paymentPassword, and the response includes payId, payStatus and updateTime; POST / api / v1 / orders / {orderId} / cancel (cancel order), the path parameter is orderId, and the response includes cancelResult and updateTime; POST / api / v1 / orders / {orderId} / ship (shipping), the path parameter is orderId, the request parameters include logisticsCompany and logisticsNo, and the response includes shipResult and updateTime; POST / api / v1 / orders / {orderId} / deliver (confirm receipt), with the path parameter being orderId, and the response includes deliveryResult and updateTime; GET / api / v1 / orders / {orderId} (query order), the path parameter is orderId. The response contains complete order information such as orderId, userId, amount, status, items, createTime, updateTime, etc. After parsing, a unified format interface metadata is generated, which includes information such as interface path, request method, parameter type, response structure, status code definition, etc.

[0026] The domain-interface mapping module establishes mapping relationships through semi-automatic inference (combining field name similarity and schema alignment) and manual completion: For entity attribute mapping, Order.id ↔ the orderId field in all interface responses, Order.userId ↔ the userId in the request and response, Order.amount ↔ the amount in the response, and Order.items[].productId ↔ the items[].productId in the request and response. It supports path expression parsing (such as mapping elements of the items array) and type conversion (such as automatic adaptation of the Decimal type amount to the number type in the interface JSON). The mapping from domain behaviors to interface collections is as follows: CreateOrder ↔ POST / api / v1 / orders + GET / api / v1 / orders / {orderId} (query and verify after creation), PayOrder ↔ POST / api / v1 / orders / {orderId} / pay + GET / api / v1 / orders / {orderId}, CancelOrder ↔ POST / api / v1 / orders / {orderId} / cancel + GET / api / v1 / orders / {orderId}, ShipOrder ↔ POST / api / v1 / orders / {orderId} / ship + GET / api / v1 / orders / {orderId}, DeliverOrder ↔ POST / api / v1 / orders / {orderId} / deliver + GET / api / v1 / orders / {orderId}, QueryOrder ↔ GET / api / v1 / orders / {orderId}; The state transition mapping is as follows: CREATED → PAID ↔ POST / api / v1 / orders / {orderId} / pay (successful response) + GET / api / v1 / orders / {orderId} (status=PAID), CREATED → CANCELED ↔ POST / api / v1 / orders / {orderId} / cancel (successful response) + GET / api / v1 / orders / {orderId} (status=CANCELED), PAID → SHIPPED ↔ POST / api / v1 / orders / {orderId} / ship (successful response) + GET / api / v1 / orders / {orderId} (status=SHIPPED), SHIPPED → DELIVERED ↔ POST / api / v1 / orders / {orderId} / deliver (successful response) + GET / api / v1 / orders / {orderId} (status=DELIVERED); The mapping from rules / invariants to assertion templates is as follows: "Order payment amount must not exceed the user's current available balance" ↔ assertion expression "userBalance ≥ order.amount" (executed before the PayOrder interface request), "Cancelled orders cannot be paid" ↔ assertion expression "order.status != CANCELED" (executed before the PayOrder interface request), "After payment, the order status is PAID" ↔ assertion expression "response.status == PAID" (executed after the PayOrder interface response).

[0027] The test case generation module executes according to preset steps: S1 reads the domain model version V1.0 and the interface contract version V1.0, and completes model syntax verification (such as the legality of state transition paths), contract format verification (such as parameter type consistency) and normalization processing (such as unifying field naming format). S2 constructs a mapping graph Gmap, where nodes contain Order entities, amount attributes, payment rules, CREATED status, PayOrder behaviors, payment interfaces, etc., and edges represent mappings and dependencies such as "Order.amount maps to the response amount field" and "PayOrder behavior is associated with the payment interface". S3 generates test paths according to the coverage strategy. The state transition path includes all 4 legal transitions and 2 illegal transitions (such as PAID→CANCELED, SHIPPED→CREATED). The business link path includes "Create order - Payment - Shipment - Confirm receipt" and "Create order - Cancel". S4 orchestrates the interface steps for each path. Taking the path "CREATED→PAID" as an example, the prerequisite steps are to call the create order interface to generate an order in the CREATED status and check the user's balance to ensure sufficient balance. The action step is to call the payment interface, and the verification step is to call the query order interface. Taking the invalid path "PAID→CANCELED" as an example, the prerequisite steps are to create an order and complete the payment. The action step is to call the cancel order interface, and the verification step is to check the response error code and prompt message. S5 transforms paths and steps into use case descriptions in the Given-When-Then format, such as "Given: The user is logged in and has sufficient balance, creating an order with a CREATED status; When: The payment interface is called to submit a payment request." Then the payment interface returns a success status code, and the order query interface returns a status of PAID and an order updateTime of approximately the current time.

[0028] Ultimately, 28 test cases were generated, covering forward, reverse, boundary, combination, and chain scenarios. A test case dependency graph was also generated, clearly defining the "Create Order" test case as a prerequisite for the "Pay Order" and "Cancel Order" test cases.

[0029] The test data generation module generates multiple types of test data based on domain constraints and strategies: positive data includes order data where userId is a valid UUID, items contain 2 products (productId is a valid code, quantity=2, unitPrice=199.99), amount=399.98, and the user balance is 1000 yuan; The reverse data includes scenario data such as amount=-100 yuan (violation of amount constraint), items is an empty array (violation of non-empty constraint), user balance=100 yuan and order amount=500 yuan (violation of payment rules), and attempted cancellation of a paid order (violation of state constraint); the boundary data includes amount=0.01 yuan (minimum value), amount=999999.99 yuan (maximum value), items contains 100 items (array upper limit), quantity=1 (minimum value), unitPrice=9999.99 yuan (maximum value), etc. All data supports a random seed of 123456 to ensure consistent results each time. Tenant isolation (assigning independent tenant IDs to test orders) and data cleanup strategies (deleting test order records after the test is completed) are also configured.

[0030] The assertion generation module automatically generates assertion sets: field assertions include validation of all interface response status codes (e.g., 200 for success and 400 for invalid status), validation of the existence of required fields (e.g., order responses must include orderId and status), and the amount field must be numeric and its range must meet constraints. Rule assertions include "payment amount ≤ user balance", "order cancellation is only allowed by the order creator", and "logistics information is not empty after shipment". Cross-interface consistency assertions include "order information queried after order creation is consistent with the creation request parameters", "order status queried after payment is consistent with the payment response status", "logistics information queried after shipment is consistent with the shipment request parameters", and "data returned by multiple queries of the same order is consistent (idempotency)". Time-series / concurrency assertions include "if two payment requests are initiated for the same order at the same time, only one will succeed" and "repeated calls to the order query interface will return consistent results".

[0031] The code generation module uses a Java + JUnit5 template engine to output test projects: The interface client encapsulation class uniformly handles interface authentication (adding Authorization request header), signature (generating request signature according to platform algorithm), retries (retrying 3 times for payment interface timeout), timeout (setting a 5-second timeout), logging (recording request parameters and response results), and trace ID (generating a unique traceId for each request), ensuring consistency with the interface contract; The data factory class encapsulates the forward order data constructor (createNormalOrder()), the reverse data constructor (createInvalidAmountOrder()), and the boundary data constructor (createMaxAmountOrder()), supporting the creation and cleanup of dependent data (such as automatically creating test users and balances before creating orders); The assertion library includes utility classes such as AmountAssert (amount-related assertion), StatusAssert (status-related assertion), and ConsistencyAssert (cross-interface consistency assertion), and provides methods such as isValidAmount(), isStatusPaid(), and isCreateAndQueryConsistent(). Test case code is organized by domain behavior, generating test classes such as OrderCreateTest, OrderPayTest, and OrderCancelTest. Each test class contains test methods for the corresponding scenario. For example, OrderPayTest contains methods such as successPay(), insufficientBalancePay(), and canceledOrderPay(), forming a test suite that can be run directly. The configuration file includes the test environment domain name (test-api.ecommerce.com), account pool (3 test user accounts and passwords), and token acquisition method (generated by calling the login interface). The report configuration supports generating HTML format test reports, which include statistics on test case execution results, business rule coverage (92% in this case), and state transition coverage (100% in this case).

[0032] The execution and feedback module runs the test project, executes all 28 test cases, and outputs 25 pass and 3 fail results. The failed test cases include "Order creation with extremely long product description" (not configured in the model due to interface field length limit) and "Concurrent payment for the same order" (due to the system's concurrent processing logic being inconsistent with expectations). The failure information is fed back into the domain model and generation strategy. The technical staff adds a length constraint (≤500 characters) to the product description field in the domain model. The system optimizes the assertion logic of concurrent use cases (adjusts the expected result of conflict handling) to provide an optimization basis for subsequent iterations.

[0033] Example 2: Implementation of Interface Test Code Generation Based on Financial Account Domain. This example is applied to the account management business of a bank's core system, focusing on core interfaces such as account opening, transfer, freezing, and unfreezing. This system automates the generation of business semantic-driven test code. The specific implementation is as follows: In the domain model management module, an account domain model is built (version V1.0, stored in JSON format): the domain entity is Account{ accountNo: String, userName: String, balance: Decimal, status: Enum, transactionRecords: Array}, and TransactionRecord contains attributes such as transId, transType, amount, transTime, and remark; The entity relationship is one of containment between Account and TransactionRecord, with one Account corresponding to multiple TransactionRecords. Attribute constraints are: accountNo conforms to bank account coding rules (16-digit number), userName is not empty and has a length of 1-20 characters, balance ≥ 0, status ∈ {NORMAL, FROZEN, CLOSED}, and transAmount in transactionRecords is not zero.

[0034] Domain rules and invariants are described using rule engine syntax: "The decrease in the balance of the transferring account after the transfer is equal to the increase in the balance of the receiving account", "A frozen account cannot initiate a transfer", "An account cannot perform any transaction operations after it is closed", and "The same transfer transaction number is unique".

[0035] State machine defines state transitions: NORMAL→FROZEN (triggering behavior: FreezeAccount, triggering condition: account has risky transactions or manual freeze instruction, action: record the reason and time of freeze), FROZEN→NORMAL (triggering behavior: UnfreezeAccount, triggering condition: risk is resolved or freeze period expires, action: record unfreeze time), NORMAL→CLOSED (triggering behavior: CloseAccount, triggering condition: user actively closes account and account balance is 0, action: record account closure time).

[0036] Domain behaviors include opening an account (OpenAccount), transferring funds (TransferAccount), freezing an account (FreezeAccount), unfreezing an account (UnfreezeAccount), closing an account (CloseAccount), querying the balance (QueryBalance), and querying transaction records (QueryTransaction). The input for TransferAccount is transferout accountNo, transferin accountNo, transAmount, and transPassword. The prerequisites are that the transferout account status is NORMAL, the balance is greater than or equal to transAmount, and the password is correct. The post-processing effect is to update the balances of the transferout and transferin accounts and generate two transaction records (transferout / transferin).

[0037] The coverage objectives and strategies are set as follows: coverage of key business paths (account opening-transfer-query), full coverage of state migration, coverage of amount boundaries (such as a transfer amount of 0.01 yuan, a maximum daily transfer limit of 50,000 yuan), and coverage of abnormal scenarios (such as transfers to non-existent accounts, transfers from frozen accounts).

[0038] The interface contract parsing module parses the Swagger contract provided by the bank and generates 7 core interface metadata: POST / api / bank / accounts (account opening), the request parameters include userName, idCardNo, and phoneNo, and the response includes accountNo, status, and createTime; POST / api / bank / transfers (transfers), the request parameters include fromAccountNo, toAccountNo, transAmount, and transPassword, and the response includes transId, transStatus, and transTime; POST / api / bank / accounts / {accountNo} / freeze (freeze account), the path parameter is accountNo, the request parameters include freezeReason, and the response includes freezeResult and freezeTime; POST / api / bank / accounts / {accountNo} / unfreeze (unfreeze account), the path parameter is accountNo, and the response includes unfreezeResult and unfreezeTime; POST / api / bank / accounts / {accountNo} / close (close account), the path parameter is accountNo, and the response includes closeResult and closeTime; GET / api / bank / accounts / {accountNo} / balance (query balance), the path parameter is accountNo, and the response includes accountNo, balance, and queryTime; GET / api / bank / accounts / {accountNo} / transactions (query transaction records), the path parameter is accountNo, the request parameters include startTime and endTime, and the response includes the transactionRecords array.

[0039] The domain-interface mapping module establishes mapping relationships: Entity attributes are mapped to Account.accountNo ↔ the accountNo field of all interfaces, Account.balance ↔ the balance field of the balance query interface, and TransactionRecord.transId ↔ the transId field of the transfer interface; Domain behaviors are mapped to OpenAccount ↔ POST / api / bank / accounts + GET / api / bank / accounts / {accountNo} / balance, TransferAccount ↔ POST / api / bank / transfers + GET / api / bank / accounts / {fromAccountNo} / balance + GET / api / bank / accounts / {toAccountNo} / balance + GET / api / bank / accounts / {fromAccountNo} / transactions, FreezeAccount ↔ POST / api / bank / accounts / {accountNo} / freeze + GET / api / bank / accounts / {accountNo} / balance (status check); The state transition mapping is NORMAL→FROZEN ↔ The freeze interface successfully responds + the balance query interface returns status=FROZEN; the rule mapping is "transfer amount equals balance change" ↔ the assertion expression "original balance of the transfer-out account - new balance of the transfer-out account = transAmount and new balance of the transfer-in account - original balance of the transfer-in account = transAmount".

[0040] The test case generation module generates 32 test cases, including positive test cases such as successful account opening, successful transfer, and successful account freezing; negative test cases such as transfer amount exceeding balance, frozen account transfer, and transaction after account closure; boundary test cases such as transfer amount of 0.01 yuan and 50,000 yuan; and complete link test cases for "account opening-transfer-freeze-unfreeze-account closure".

[0041] The use case steps are clearly arranged. For example, the prerequisite steps for a successful transfer use case are to create two accounts in NORMAL state and deposit 10,000 yuan into each account. The action steps are to call the transfer interface to transfer 2,000 yuan. The verification steps are to query the balance and transaction records of the two accounts.

[0042] The test data generation module generates positive data: account opening data with userName as "Zhang San", idCardNo as a valid number, and phoneNo as a valid mobile phone number, with a transfer amount of 2000 yuan and sufficient balance in the transferring account; Reverse data: Transfer amount 60,000 yuan (exceeding the daily limit), toAccountNo is a non-existent account, transPassword is incorrect, transfer initiated by a frozen account; Boundary data: transAmount = 0.01 yuan (minimum value), transAmount = 50000 yuan (maximum value), account balance = 0 yuan (prerequisite for account closure); It supports random seeds and data isolation, with test accounts and production accounts belonging to different database schemas. Test accounts and transaction records are automatically deleted after the test ends.

[0043] The assertion generation module generates assertions: field assertions include the transfer interface response transId being non-empty and the balance field being a non-negative number; The rule assertions include "the balance change after the transfer is as expected" and "the frozen account returned error code 1003 for the transfer"; Cross-interface consistency assertions include "the balance of the transferring account after the transfer + the balance of the receiving account = the total balance before the transfer" and "the transaction record query includes this transfer record". The timing / concurrency assertions include "two transfers initiated simultaneously from the same account, with the total transfer amount not exceeding the account balance" and "repeated queries of transaction records return consistent results".

[0044] The code generation module outputs a Python+Pytest test project, which includes an interface client (handling special authentication methods for bank interfaces), a data factory (encapsulating account opening data and transfer data construction), an assertion library (implementing balance consistency and transaction record verification), test case code, and configuration files.

[0045] After the execution and feedback module runs, it outputs a test report showing that the business rule coverage is 95%, and feeds back the failure information of "balance calculation error during concurrent transfer" to optimize the concurrent processing rules in the domain model.

[0046] Example 3: Implementation of Interface Test Code Generation Based on Logistics and Delivery Domain. This example focuses on a logistics and delivery system, targeting core processes such as order creation, door-to-door pickup, logistics transfer, and delivery confirmation. It utilizes this system to automate the generation and execution of interface test code. The specific implementation is as follows: The domain model management module constructs a logistics and delivery domain model (version V1.0, DSL format): The domain entity is DeliveryOrder{ orderNo: String, senderInfo: Sender, receiverInfo: Receiver, goodsInfo: Goods, deliveryStatus: Enum, logisticsRecords: Array}, where Sender contains name, phone, and address, Receiver has the same structure as Sender, Goods contains name, weight, volume, and type, and LogisticsRecord contains logisticsCompany, logisticsNo, nodeName, nodeTime, and statusDesc; the relationship between entities is that DeliveryOrder contains senderInfo, receiverInfo, goodsInfo, and multiple logisticsRecords.

[0047] Attribute constraints: For senderInfo and receiverInfo, phone must be an 11-digit valid mobile phone number and address must be non-empty; for goodsInfo, weight > 0 (in kg) and volume > 0 (in m). 3 ), deliveryStatus∈{CREATED,PICKED, IN_TRANSIT, ARRIVED, DELIVERED, CANCELLED}, and the nodeTime of logisticsRecords is sorted in ascending order of time.

[0048] Domain rules and invariants: "Logistics status transition is irreversible (CREATED→PICKED→IN_TRANSIT→ARRIVED→DELIVERED)" "Cancelled orders cannot be picked up, transferred, or otherwise processed" "The weight of goodsInfo is ≤50kg (the limit for ordinary express delivery)" "The statusDesc of each node in logisticsRecords matches the deliveryStatus".

[0049] The state machine defines 5 legal transition paths and multiple illegal transitions, such as CREATED→PICKED (triggered by PickGoods), PICKED→IN_TRANSIT (triggered by TransferGoods), IN_TRANSIT→ARRIVED (triggered by ArriveHub), ARRIVED→DELIVERED (triggered by DeliverGoods), and CREATED→CANCELLED (triggered by CancelDelivery). The triggering conditions include "the order status is CREATED when picking up the package" and "the logistics record has been updated at the pickup node during transit".

[0050] Domain behaviors include creating a delivery order (CreateDelivery), picking up goods (PickGoods), transferring goods (TransferGoods), arriving at a hub (ArriveHub), delivering and signing for goods (DeliverGoods), canceling an order (CancelDelivery), and querying logistics (QueryLogistics). The input for CreateDelivery is senderInfo, receiverInfo, and goodsInfo. The prerequisite is that the sender and recipient information are complete. The result is that a DeliveryOrder is generated and an orderNo is assigned. The PickGoods input is orderNo and courierId. The prerequisite is that the order status is CREATED. The post-event effects are updating deliveryStatus to PICKED and adding a pickup node logistics record. The coverage goals and strategies are full coverage of status transitions, full delivery link coverage, weight / volume boundary coverage, and illegal status transition coverage.

[0051] The interface contract parsing module parses the Postman collection of the logistics system to export the contract and generates 7 interface metadata: POST / api / logistics / orders (create delivery order), the request parameters include senderInfo, receiverInfo, and goodsInfo, and the response includes orderNo, deliveryStatus, and createTime; POST / api / logistics / orders / {orderNo} / pick (door pickup), the path parameter is orderNo, the request parameters include courierId and pickTime, and the response includes pickResult and updateTime; POST / api / logistics / orders / {orderNo} / transfer (logistics transfer), with orderNo as the path parameter, request parameters including logisticsCompany and hubName, and response including transferResult and updateTime; POST / api / logistics / orders / {orderNo} / arrive (arrive at hub), with the path parameter being orderNo. The request parameters include hubName and arrivalTime, and the response includes arrivalResult and updateTime. POST / api / logistics / orders / {orderNo} / deliver (delivery and receipt confirmation), the path parameter is orderNo, the request parameters include receiverSign and deliveryTime, and the response includes deliveryResult and updateTime; POST / api / logistics / orders / {orderNo} / cancel (cancel order), with orderNo as the path parameter. The response includes cancelResult and updateTime. GET / api / logistics / orders / {orderNo} / logistics (query logistics), with orderNo as the path parameter. The response includes logisticsRecords and currentStatus.

[0052] The domain-interface mapping module establishes the following mappings: entity attributes are mapped to DeliveryOrder.orderNo ↔ the orderNo field of all interfaces, senderInfo.phone ↔ the senderPhone field in the request and response, and goodsInfo.weight ↔ the goodsWeight field in the request and response; The domain behavior is mapped as CreateDelivery ↔ POST / api / logistics / orders + GET / api / logistics / orders / {orderNo} / logistics, PickGoods ↔ POST / api / logistics / orders / {orderNo} / pick + GET / api / logistics / orders / {orderNo} / logistics, TransferGoods ↔ POST / api / logistics / orders / {orderNo} / transfer + GET / api / logistics / orders / {orderNo} / logistics; The state transition mapping is CREATED→PICKED ↔ Successful response from the pickup interface + return of currentStatus=PICKED from the logistics query interface, which includes the pickup logistics node; the rule mapping is "weight≤50kg" ↔ assertion expression "goodsInfo.weight ≤50" (the endpoint is the validation before the order creation interface request), "state transition is irreversible" ↔ assertion expression "current state sorting ≥ previous state sorting" (the endpoint is the validation after each operation interface response).

[0053] The test case generation module generates 35 test cases, covering forward flow (creation-pickup-transfer-arrival-delivery), reverse scenarios (overweight order creation, cancellation of picked-up orders, status rollback operations), and edge cases (goodsInfo.weight=50kg, weight=0.01kg, volume=0.001m). 3 The combined scenarios (order creation followed by cancellation, or delayed arrival after transit) clearly demonstrate in the use case dependency diagram that "creating a delivery order" is a prerequisite for all subsequent operation-related use cases.

[0054] The test data generation module generates positive data: the senderInfo and receiverInfo have an 11-digit valid phone number and a detailed and complete address; the goodsInfo has the name "electronic product," weight = 5kg, and volume = 0.02m. 3 ; Reverse data: goodsInfo.weight=55kg (overweight), senderInfo.phone is a 10-digit number (illegal phone number), attempted cancellation of a picked-up order; Boundary data: weight=0.01kg, weight=50kg, volume=0.001m 3 The address is an extremely long string (100 characters). It supports environment variable injection (such as the name of the logistics hub in the test environment), account pool isolation (test courier accounts are independent), and test data is automatically cleaned up after execution.

[0055] The assertion generation module generates assertions: field assertions include all interface response status codes, the existence of required fields, and the weight field being of numeric type; The rule assertions include "Overweight order creation returned error code 2001" and "Status transition conforms to the irreversible rule"; Cross-interface consistency assertions include "logistics records queried after order creation contain initial status", "logistics records queried after pickup have added pickup nodes", and "currentStatus queried after delivery is DELIVERED". The timing / concurrency assertions include "If a pickup and cancellation request is initiated for the same order at the same time, only one operation is successful" and "Duplicate queries of logistics records return consistent results".

[0056] The code generation module outputs a JavaScript+Jest test project, which includes an interface client (handling token authentication and request encryption for the logistics system), a data factory, an assertion library, test case code, and configuration report files. After the execution and feedback module runs, it outputs a coverage report, feeds back the issue of "failed to create an order with an extremely long address" to the domain model, adds a length constraint (≤80 characters) to the address field, and subsequently incrementally regenerates the relevant test cases.

[0057] Working principle: First, the domain model management module provides a versionable domain model containing core business semantics. The interface contract parsing module parses the interface metadata. Then, the domain-interface mapping module establishes the relationship between the two, providing a mapping basis for subsequent generation. The test case generation module generates test cases covering multiple scenarios based on the model and mapping. The test data generation module generates controllable and reproducible test data according to constraints. The assertion generation module converts business rules into executable assertions. Then, the code generation module outputs executable test projects in multiple languages ​​and frameworks through the template engine. Finally, the execution and feedback module runs the tests and feeds back the results to optimize the model and generation strategy. When the domain model or interface contract changes, the system uses version difference comparison and impact analysis to incrementally regenerate the affected parts, ensuring that the test code evolves synchronously with business rules and interface contracts.

[0058] The above description is only a preferred embodiment of the present invention, but the scope of protection of the present invention is not limited thereto. Any equivalent substitutions or modifications made by those skilled in the art within the scope of the technology disclosed in the present invention, based on the technical solution and inventive concept of the present invention, should be covered within the scope of protection of the present invention.

Claims

1. A domain model-based interface test code generation system, characterized in that, The interface test code generation system includes a domain model management module, an interface contract parsing module, a domain-interface mapping module, a test case generation module, a test data generation module, an assertion generation module, a code generation module, and an execution and feedback module. The functions of each module are as follows: Domain Model Management Module: Used to create, import, and edit domain models, perform syntax and consistency checks, and manage model versions; Interface contract parsing module: used to parse OpenAPI / Swagger / Postman or custom interface descriptions and generate unified interface metadata; Domain-Interface Mapping Module: Used to establish the mapping relationship between domain objects / behaviors / state transitions and interfaces, forming a mapping table and mapping rules; Test case generation module: Generates forward, backward, boundary, composite, state transition, and link test cases based on the domain model and mapping rules, and generates a test case dependency graph; Test data generation module: Generates test data based on domain constraints and strategies, including pre-existing data, abnormal data, boundary data, and reproducible random data; Assertion generation module: Generates field assertions, rule assertions, and cross-interface consistency assertions based on domain rules, invariants, and mapping relationships; Code generation module: Outputs execution interface test project code based on a template engine; Execution and Feedback Module: Executes the generated test project, outputs coverage and failure information, and feeds it back into the model and generation strategy to optimize subsequent generation.

2. The interface test code generation system based on a domain model according to claim 1, characterized in that, The domain model includes: Domain entities: users, orders, accounts, including attributes and relationships between entities; Attribute constraints: type, length, value range, enumeration, regular expression, uniqueness, NOT NULL, cross-field constraints; Domain rules and invariants: Describe business constraints using execution expressions, rule engine syntax, or DSL; State machine: Defines a set of states and transition relationships, with each transition carrying a triggering condition and an action; Domain behaviors / use cases: creation, payment, cancellation, query, etc., and define inputs, outputs, preconditions and post-effects; Coverage objectives and strategies: full state transition coverage, critical path coverage, error code coverage, and boundary coverage.

3. The interface test code generation system based on a domain model according to claim 1, characterized in that, The domain model is expressed in JSON / YAML / DSLw file format or graph model and supports version management.

4. The interface test code generation system based on a domain model according to claim 1, characterized in that, The domain-interface mapping module includes: Mapping of entity attributes to request / response fields: Supports bidirectional mapping between business object attributes and interface fields, including path expression parsing and type conversion rules; Mapping of domain behaviors to interface sets: One domain behavior corresponds to one or more interfaces; Mapping state transitions to interface call sequences: binding state machine transitions to the sequence of executed interface steps and verification steps; Mapping from rules / invariants to assertion templates: Mapping domain rules to the execution of assertion expressions and assertion endpoints.

5. The interface test code generation system based on a domain model according to claim 1, characterized in that, The mapping relationship is obtained through manual configuration, semi-automatic derivation, or extraction from code annotations / domain service descriptions.

6. The interface test code generation system based on a domain model according to claim 1, characterized in that, The test case generation module includes the following steps: S1: Read the domain model version Vd and the interface contract version Va, and complete the model and contract parsing, verification and normalization; S2: Construct a mapping graph Gmap, where nodes contain entities / attributes / rules / states / behaviors / interfaces, representing mappings and dependencies; S3: Generate test paths according to coverage strategy: If a state machine exists, generate a set of state transition paths; if a behavior chain exists, generate a behavior dependency sequence. S4: Generate interface steps for each path: including pre-steps, action steps, and verification steps; S5: Convert paths and steps into use case descriptions and output them to the code generator.

7. The interface test code generation system based on a domain model according to claim 1, characterized in that, The test data generation module includes: Positive data: When all constraints and preconditions are met, the expected business behavior and state transition are triggered; Reverse data: selective constraint violation, used for abnormal paths and error code overriding; Boundary data: minimum / maximum value, empty string, extremely long string, special characters, date thresholds, empty / full sets, etc., used for boundary coverage; Reproducibility and isolation: Supports random seed, environment variable injection, tenant / account pool isolation, data cleanup and rollback strategies.

8. The interface test code generation system based on a domain model according to claim 1, characterized in that, The assertion generation module includes: Field assertions: response status code, error code, existence of fields that must be returned, field type and range validation; Rule assertions: Convert domain rules / invariants into execution assertion expressions; Cross-interface consistency assertions: consistency after creation, consistency after modification, consistency during state transition, read-write consistency, and idempotency verification; Timing / Concurrency Assertions: Based on domain idempotency rules, verify the consistency of results for duplicate requests, the handling of concurrent conflicts, and the effectiveness of retries.

9. The interface test code generation system based on a domain model according to claim 1, characterized in that, The code generation module includes: Interface client encapsulation: Unified handling of authentication, signature, retries, timeouts, logging and tracking IDs, and consistency with the interface contract; Data factories and fixtures: encapsulate forward / reverse / boundary data construction, and support dependency data creation and cleanup; Assertion library: Implements field assertions, rule assertions, and cross-interface consistency assertions to improve reusability and maintainability; Test case code: Organize test classes and test case methods according to domain behavior or state machine path to form a runnable test suite; Configuration and Reporting: Generate environment configuration files, test report output, and statistical data on test case coverage and business rule coverage.