Mock object adjusting method and device, electronic equipment and storage medium

By combining the current and historical test return results of the Mock object and using the Mock rule prediction model to dynamically adjust the Mock rules, the problem of low efficiency in Mock object adjustment in the existing technology is solved, and efficient adjustment and consistency of Mock objects in automated testing are achieved.

CN120705057AActive Publication Date: 2025-09-26北京领雁科技股份有限公司
View PDF 4 Cites 0 Cited by

Patent Information

Application Number
CN202510882041.6
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2025-06-27
Publication Date
2025-09-26
Estimated Expiration
2045-06-27

AI Technical Summary

Technical Problem

Existing Mock object adjustment methods are difficult to adapt to the rapid changes in the test environment and external dependencies, resulting in low adjustment efficiency of Mock objects in automated testing.

Method used

By combining the current and historical test return results of the Mock object, the Mock rules are dynamically adjusted using the Mock rule prediction model to improve the adjustment efficiency of the Mock object.

Benefits of technology

It enables efficient adjustment of Mock objects in automated testing, ensures high consistency and stability between Mock rules and real business scenarios, and improves the independence and efficiency of testing.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN120705057A_ABST
    Figure CN120705057A_ABST
Patent Text Reader

Abstract

The invention provides a Mock object adjusting method and device, electronic equipment and a storage medium. The Mock object adjusting method comprises the steps that dependency information of each external dependency of a target program is extracted from the target program to be tested; aiming at any external dependency, based on the dependency information of the external dependency, determining a Mock object of the external dependency and a Mock rule of the Mock object; for any Mock object, based on the Mock rule of the Mock object, carrying out a call test on the Mock object to obtain a current test return result of the Mock object; and dynamically adjusting the Mock rule of the Mock object based on the current test return result and the historical test return result of the Mock object and the Mock rule prediction model. Thus, the Mock rule is dynamically adjusted through the Mock rule prediction model in combination with the current and historical test return results of the Mock object, and the adjustment efficiency of the Mock object in the automatic test is improved.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] The present application relates to the field of automated testing technology, and in particular to a method, device, electronic device, and storage medium for adjusting a mock object. Background Art

[0002] As the software development lifecycle continues to evolve, automated testing plays an increasingly important role in improving software quality, reducing development costs, and accelerating product iteration. Especially in continuous integration (CI) and continuous delivery (CD) environments, automated testing has become a core component for ensuring software stability and reliability.

[0003] When performing automated testing, the test code often depends on external services (such as databases, web services, and message queues). The uncontrollability, unpredictability, and operational costs of these external services make tests fragile, unstable, and inefficient. Traditional solutions often rely on mock objects to simulate these external dependencies.

[0004] However, with the ever-changing automated testing environment and the dynamic changes in external dependencies, mock object rules need to be frequently updated to ensure the accuracy and consistency of mock objects' simulations of external dependencies. Existing mock object adjustment methods rely on manual code to adjust and update mock rules, which is difficult to adapt to the rapid changes in the test environment and external dependencies, resulting in low mock object adjustment efficiency in automated testing. Summary of the Invention

[0005] In view of this, the embodiments of the present application at least provide a method, device, electronic device and storage medium for adjusting the Mock object, which combines the current and historical test return results of the Mock object and dynamically adjusts the Mock rules through the Mock rule prediction model, thereby improving the adjustment efficiency of the Mock object in automated testing.

[0006] This application mainly includes the following aspects: In a first aspect, an embodiment of the present application provides a method for adjusting a mock object, the method comprising: extracting dependency information of each external dependency of the target program to be tested from the target program to be tested; for any of the external dependencies, determining the mock object of the external dependency and the mock rule of the mock object based on the dependency information of the external dependency; for any of the mock objects, calling and testing the mock object based on the mock rule of the mock object to obtain the current test return result of the mock object; dynamically adjusting the mock rules of the mock object based on the current test return result of the mock object, historical test return results and a mock rule prediction model.

[0007] In the second aspect, an embodiment of the present application also provides a device for adjusting a Mock object, the device for adjusting a Mock object comprising: a data acquisition module for extracting dependency information of each external dependency of the target program to be tested from the target program to be tested; a rule determination module for determining, for any of the external dependencies, the Mock object of the external dependency and the Mock rule of the Mock object based on the dependency information of the external dependency; a test execution module for calling and testing the Mock object for any of the Mock objects based on the Mock rule of the Mock object to obtain the current test return result of the Mock object; a rule adjustment module for dynamically adjusting the Mock rules of the Mock object based on the current test return result of the Mock object, the historical test return result and the Mock rule prediction model.

[0008] In a third aspect, an embodiment of the present application further provides an electronic device comprising: a processor, a memory and a bus, wherein the memory stores machine-readable instructions executable by the processor, and when the electronic device is running, the processor and the memory communicate through the bus, and the machine-readable instructions are executed by the processor to execute the steps of the Mock object adjustment method as described above.

[0009] In a fourth aspect, an embodiment of the present application further provides a computer-readable storage medium, on which a computer program is stored. When the computer program is executed by a processor, the steps of the method for adjusting the Mock object as described above are executed.

[0010] The adjustment method, device, electronic device and storage medium of the Mock object provided in the embodiment of the present application extract the dependency information of each external dependency of the target program from the target program to be tested; for any external dependency, based on the dependency information of the external dependency, determine the Mock object of the external dependency and the Mock rule of the Mock object; for any Mock object, based on the Mock rule of the Mock object, call the Mock object for testing to obtain the current test return result of the Mock object; based on the current test return result of the Mock object, the historical test return result and the Mock rule prediction model, dynamically adjust the Mock rule of the Mock object. In this way, in combination with the current and historical test return results of the Mock object, the Mock rules are dynamically adjusted through the Mock rule prediction model, thereby improving the adjustment efficiency of the Mock object in the automated test.

[0011] In order to make the above-mentioned objects, features and advantages of the present application more obvious and easy to understand, preferred embodiments are given below and described in detail with reference to the accompanying drawings. BRIEF DESCRIPTION OF THE DRAWINGS

[0012] In order to more clearly illustrate the technical solutions of the embodiments of the present application, the following is a brief introduction to the drawings required for use in the embodiments. It should be understood that the following drawings only show certain embodiments of the present application and therefore should not be regarded as limiting the scope. For ordinary technicians in this field, other relevant drawings can be obtained based on these drawings without creative work.

[0013] Figure 1 A flowchart of a method for adjusting a Mock object provided in an embodiment of the present application is shown; Figure 2 One of the functional module diagrams of a Mock object adjustment device provided in an embodiment of the present application is shown; Figure 3 A second functional module diagram of a device for adjusting a Mock object provided in an embodiment of the present application is shown; Figure 4 A schematic structural diagram of an electronic device provided in an embodiment of the present application is shown. DETAILED DESCRIPTION

[0014] In order to make the purpose, technical solutions and advantages of the embodiments of the present application clearer, the technical solutions in the embodiments of the present application will be clearly and completely described below in conjunction with the drawings in the embodiments of the present application. It should be understood that the drawings in the present application only serve the purpose of illustration and description and are not used to limit the scope of protection of the present application. In addition, it should be understood that the schematic drawings are not drawn to scale. The flowcharts used in this application illustrate the operations implemented according to some embodiments of the present application. It should be understood that the operations of the flowcharts can be implemented out of sequence, and steps without logical context can be reversed or implemented simultaneously. In addition, those skilled in the art, under the guidance of the contents of this application, can add one or more other operations to the flowchart, or remove one or more operations from the flowchart.

[0015] In addition, the described embodiments are only a part of the embodiments of the present application, rather than all of the embodiments. The components of the embodiments of the present application generally described and shown in the drawings here can be arranged and designed in various configurations. Therefore, the following detailed description of the embodiments of the present application provided in the drawings is not intended to limit the scope of the claimed application, but merely represents selected embodiments of the present application. Based on the embodiments of the present application, all other embodiments obtained by those skilled in the art without making creative work are within the scope of protection of the present application.

[0016] To facilitate understanding of the present application, the technical solutions provided in the present application are described in detail below in conjunction with specific embodiments.

[0017] See also Figure 1 , Figure 1 This is a flowchart of a method for adjusting a Mock object provided in an embodiment of the present application. Figure 1 As shown, the adjustment method of the Mock object provided in the embodiment of the present application includes the following steps: S101 , extracting dependency information of each external dependency of a target program to be tested from the target program.

[0018] Here, static code analysis technology is used to scan the code base of the target program through an automated tool (such as Eclipse JDT), and the dependency information of each external dependency of the target program is extracted from the target program to be tested. Among them, external dependencies refer to external resources or components that a software project depends on during operation or construction. These dependencies are usually not part of the project itself, but are provided by a third party or generated by other projects. In an embodiment of the present application, the dependency type of the external dependency includes at least one of database dependency, HTTP API dependency, and message queue dependency; the dependency information of the external dependency records the type, calling method and related parameters of the external dependency, specifically including the dependent object name, calling location, dependency type and key parameter information of the external dependency. By extracting the dependency information of the external dependency, data support can be provided for subsequent Mock object generation and adjustment.

[0019] S102 : For any of the external dependencies, determine a mock object of the external dependency and a mock rule of the mock object based on the dependency information of the external dependency.

[0020] Here, based on the dependency information of the external dependencies extracted in S101, corresponding Mock objects and Mock rules of the Mock objects are generated for each external dependency. Among them, the Mock object is a commonly used tool in software testing to simulate the behavior of real objects or external systems. The main purpose of the Mock object is to replace the real dependencies in the test environment, thereby isolating the tested code and improving the independence and efficiency of the test. Mock rules refer to a set of predefined rules for defining the behavior and response of Mock objects. Mock objects are typically used to replace real external dependencies (such as database dependencies, HTTPAPI dependencies, external service dependencies) in order to simulate the behavior of these dependencies in unit testing or integration testing. Mock rules define how the Mock object should respond under specific conditions.

[0021] In the embodiment of the present application, according to the dependency information of the external dependency, a corresponding Mock object is generated for each external dependency according to the dependency type. Specifically, external dependencies are divided into database dependencies, HTTP API dependencies and message queue dependencies according to the call type, corresponding to database mocks, HTTP API mocks and message queue mocks respectively. Among them, the calling method involving database access operations such as "findById", "query" and "execute" is identified as database dependency; the calling method involving HTTP client calls such as "getForObject", "postForObject" and "execute" is identified as HTTP API dependency. The calling method involving message queue operations such as "send" and "publish" is identified as message queue dependency.

[0022] The predefined mocking rules for database mocks are: when the call parameters meet expectations, predefined dummy data is returned; when the parameters are abnormal, the simulation throws an exception or returns an error status. For example, when the expression "orderRepository.findById(orderId)" is scanned, "orderRepository" is identified as a database dependency. The corresponding predefined mocking rules for database mocks are: if the parameter is equal to 1, dummy order data (such as Order(1, "Laptop", 10)) is returned; if the parameter is null or a negative number, the simulation throws an exception.

[0023] Specifically, the predefined rules for database mocks are implemented through the following structured configuration: "{ "normalResponse": { "condition": "params.id == 1", "template": { "id": 1, "name": "Laptop", "quantity": 10} }, "exceptionResponse": { "condition": "params.id == null || params.id<0", "template": { "type": "OrderNotFoundException", "message": "InvalidID"} } }".

[0024] HTTP API Mock's predefined mock rule directly returns a JSON data structure that matches the format of the real service response. For example, when calling "restTemplate.getForObject(...)", it identifies an HTTP API dependency. The corresponding predefined mock rule for HTTP API Mock is to return a JSON response in the format "{"status":"success","data":{"id":1,"name":"Laptop"}}".

[0025] Specifically, the predefined rules of HTTP API Mock are implemented through the following structured configuration: "{ "normalResponse": { "condition": "true", / / Unconditional return "template": { "status": "success", "data": { "id": 1, "name": "Laptop"}} }, "exceptionResponse": null / / Undefined exception response }".

[0026] The predefined mock rule for the message queue mock intercepts message sending and directly returns a confirmation message without actually transmitting the message over the network. For example, when calling "kafkaTemplate.send(...)", it identifies a message queue dependency. The corresponding predefined mock rule for the message queue mock returns the string "Message sent to order-topics successfully".

[0027] Specifically, the predefined rules of the message queue mock are implemented through the following structured configuration: "{ "normalResponse": { "condition": "true", "template": "Message sent to order-topic successfully" }, "exceptionResponse": null / / Undefined exception response }".

[0028] S103 : For any of the Mock objects, based on the Mock rules of the Mock object, perform a call test on the Mock object to obtain a current test return result of the Mock object.

[0029] Here, for any Mock object, based on the Mock rules of the Mock object, the Mock object is called and tested to obtain the current test return result of the Mock object. Specifically, the Mock object intercepts the call information of the external dependency and feeds back the current test return result according to the predefined Mock rules.

[0030] Specifically, for database mocks, to ensure that there is no need to actually connect to the database during testing, a mock framework is embedded in the system. This intercepts database query behavior by intercepting calls to database query methods (such as "findById"). When a specific query call is detected (such as "orderRepository.findById"), a predefined rule is triggered. According to the predefined rule, if the query parameters are valid, virtual order data is directly returned; if the query parameters are invalid, an exception is simulated or an error status is returned. For example, when "orderRepository.findById(1)" is called, the query is not executed and a virtual order object is directly returned. When "orderRepository.findById(-1)" or "orderRepository.findById(null)" is called, the query is not executed and an exception is directly simulated, such as an "OrderNotFoundException".

[0031] For HTTP API mocks, to ensure that no external HTTP requests are actually made in the test environment, the code captures all requests made through HTTP clients (such as RestTemplate) and uses an interception mechanism to replace real calls. Method call parameters are checked for URL strings to determine whether the call is an external API request. Based on predefined rules, JSON data is directly returned, consistent with the format of the actual service response. The returned data structure ensures that the status indicator, data, and necessary metadata are included to ensure that the test case can correctly parse the response data. For example, when the external dependency information includes the external API call "restTemplate.getForObject("https: / / api.example.com / order / 1", Order.class)", the mock object uses the interception mechanism to bypass the actual HTTP request and instead directly returns the following JSON data: "{ "status": "success", "data": { "id": 1, "name": "Laptop"}}".

[0032] For message queue mocks, to ensure that message sending and receiving in the test environment are simulated by mock objects without requiring actual network transmission, interceptors are used to capture message queue-related calls (such as the "send" method of "KafkaProducer" or "RabbitTemplate") before they occur. A set of mock return values ​​is predefined. When a message send operation is intercepted, a confirmation message is directly returned, indicating that the message has been "sent." Furthermore, confirmation results or mock message content can be returned to simulate message consumption scenarios as needed. For example, when the code calls "kafkaTemplate.send("order-topic", order)", the mock object intercepts the call and, without actually transmitting the message, directly returns a confirmation message, such as "Message sent to order-topic successfully."

[0033] S104 , dynamically adjusting the Mock rules of the Mock object based on the current test return result, the historical test return result, and the Mock rule prediction model of the Mock object.

[0034] Here, based on the dependency relationship and the Mock rule prediction model, Mock objects can be dynamically generated and the Mock rules of the Mock objects can be adjusted. In this way, the Mock object can not only simulate the behavior of external dependencies, but also adaptively adjust its behavior according to changes in business logic. Among them, the historical test return results of the Mock object are a complete historical data set consisting of the call parameters, return values ​​and exception information of the Mock object collected during the test execution process, which provides a data basis for the subsequent training of the Mock rule prediction model. Specifically, the acquisition of historical test return results can be achieved by integrating a log interceptor module in the Mock framework (such as Mockito, WireMock). For each call to the Mock object, the following information is captured and recorded: The name of the method being called (e.g., "orderRepository.findById"); Input parameters (for example: "{ "id": 1}"); Return value (for example: "{ "id": 1, "name": "Laptop", "quantity": 10}"); Exceptions (if any, record the exception type and error message); When calling the API, additional information such as the request URL and HTTP status code is recorded.

[0035] The above data is stored in different categories, for example, database mocks, HTTP API mocks, and message queue mocks are stored separately. Specifically, Kafka is used for real-time log streaming storage, and each call data is output in JSON format. Redis database is used as a short-term cache to ensure fast data access. At the same time, the data is stored in Elasticsearch for long-term trend analysis and retrieval. The JSON format output can be expressed as: "{ "mockType": "database", "method": "orderRepository.findById", "input": { "id": 1}, "output": { "id": 1, "name": "Laptop", "quantity": 10}, "timestamp": "2025-03-22T10:30:00Z", "requestCount": 150, "exceptionRate": 0.05}".

[0036] Extended storage fields include "timestamp" (recording the call time), "requestCount" (accumulated number of calls), and "exceptionRate" (exception return rate) for subsequent analysis. Finally, the collected log data is cleaned to remove null values, incomplete records, and outliers. All values ​​are normalized and the JSON structure is standardized to ensure a consistent data format. For repeated calls to the same method with the same parameters, duplicates are removed and merged to reduce data redundancy and generate historical test return results.

[0037] Furthermore, dynamically adjusting the Mock rules of the Mock object based on the current test return result, historical test return results, and the Mock rule prediction model of the Mock object includes: Step a1: Determine the current input features and the historical input features of the Mock object based on the current test return result and the historical test return result of the Mock object.

[0038] Here, the current input features and historical input features of the Mock object are extracted from the current test return results and historical test return results of the Mock object. Specifically, the input features include: API call path (e.g., " / order / {id}"); Request parameters (e.g. id=1); The number of times the same method was called in the past; Historical return data structure (including status code, return value content, etc.); Historical abnormal return rate (calculate the abnormal call ratio); Time dimension (distinguishing the stability of rules during peak and trough periods).

[0039] Among them, historical input features also include three types of data: Anomaly Frequency Matrix: This records the probability of anomalies occurring at different times and under different parameter combinations in the form of "time period x parameter value." (If a mock rule does not support exceptions, the corresponding entry in this matrix is ​​0.) Time Decay Factor: This decays older data in the "Anomaly Frequency Matrix" to highlight recent anomalies. Rule Stability Index: This measures the historical reliability of each mock rule, such as the number of rollbacks, anomaly rate fluctuations, and test pass rate. Current input features refer to the parameter values ​​and call time tags used in this test call, and are used to express the "real-time characteristics of this scenario." For mock rules that do not have configured exception responses (such as HTTP API and message queue mocks), the historical exception return rate is fixed at 0 and is not included in the calculation of exception rate-related features.

[0040] Step a2: training the Mock rule prediction model based on the historical input features of the Mock object to obtain a trained Mock rule prediction model.

[0041] Here, the machine learning model is trained based on the historical input features of the Mock object so that the trained Mock rule prediction model can extract high-frequency patterns from the historical Mock call records (historical input features), identify the optimal Mock return rules under each dependent scenario (current input features), and predict the abnormal return rate of the current rule, providing a basis for the dynamic adjustment of subsequent rules. In the embodiment of the present application, Sklearn or TensorFlow is used to build a training model. The collected historical input features are used as a training set to train the Mock rule prediction model to predict the optimal return value and abnormal rate. During the model training process, cross-validation and anomaly detection algorithms are used to eliminate abnormal data to ensure accurate model predictions. The trained model is stored as an updateable model to support dynamic query and real-time update.

[0042] Step a3: input the current input features of the Mock object into the trained Mock rule prediction model to obtain the predicted optimal return value and predicted abnormal return rate of the Mock object; the predicted abnormal return rate is generated by analyzing the abnormal frequency matrix.

[0043] Here, the current input features of the mock object are fed into the trained mock rule prediction model to obtain the predicted optimal return value and predicted abnormal return rate of the mock object. The predicted abnormal return rate is generated by analyzing the abnormal frequency matrix. The predicted optimal return value and predicted abnormal return rate of the mock object are the possible optimal return value and the probability of triggering an abnormal return in future calls of the mock object.

[0044] Step a4: dynamically adjust the Mock rules of the Mock object based on the predicted optimal return value and the predicted abnormal return rate of the Mock object.

[0045] Here, based on the predicted optimal return value and predicted abnormal return rate of the Mock object, the Mock rules of the Mock object are dynamically adjusted to ensure that the return data generated by calling the Mock object in the future always reflects the current real business scenario and maintains a high degree of accuracy and stability.

[0046] Furthermore, the Mock rule prediction model includes a decision tree module, a random forest module, and a Bayesian optimization module; the Mock rule prediction model is trained based on the historical input features of the Mock object to obtain a trained Mock rule prediction model, including: Step b1: train the decision tree module based on the historical input features of the Mock object to obtain a trained decision tree module and generate a preliminary prediction result of the Mock object; the preliminary prediction result includes a preliminary predicted return value and a preliminary predicted abnormal return rate of the Mock object.

[0047] The mock rule prediction model includes a decision tree module, a random forest module, and a Bayesian optimization module. A decision tree model is used for preliminary rule learning to identify mock return patterns under different input parameters. The historical input features of the mock object are fed into the decision tree module for training. The trained decision tree module generates preliminary prediction results for the mock object. These preliminary prediction results include the mock object's preliminary predicted return value and preliminary predicted abnormal return rate.

[0048] Step b2: training the random forest module based on the preliminary prediction results of the mock object to obtain a trained random forest module and generate an optimized prediction result of the mock object; the optimized prediction result includes the optimized prediction return value and the optimized prediction abnormal return rate of the mock object; and establishing a probabilistic coupling connection between the output node of the decision tree module and the feature sampler of the random forest module.

[0049] Here, the Random Forest model is then used to improve the generalization ability of the model and avoid overfitting. The preliminary prediction results of the Mock object are input into the Random Forest module for training. The trained Random Forest module is obtained and the optimized prediction results of the Mock object are generated. The optimized prediction results include the optimized prediction return value and the optimized prediction abnormal return rate of the Mock object. Among them, the output node of the decision tree module is connected with the feature sampler of the Random Forest module through a probabilistic coupling connection. The preliminary prediction results of the decision tree are used to guide the feature selection and sampling process of the Random Forest module, thereby improving the generalization ability and prediction accuracy of the model.

[0050] Step b3: training the Bayesian optimization module based on the optimization prediction result to obtain a trained Bayesian optimization module; the Bayesian optimization module includes a prior distribution correction unit for adjusting the Gaussian process kernel function according to the out-of-bag error of the random forest module.

[0051] Here, Bayesian optimization technology is introduced to detect and automatically adjust the model's predicted abnormal return rate by adjusting parameters. The optimized prediction results are then fed into the Bayesian optimization module for training, resulting in a trained Bayesian optimization module. The Bayesian optimization module includes a prior distribution correction unit that adjusts the Gaussian process kernel function based on the out-of-bag error of the random forest module. Specifically, the prior distribution correction unit analyzes the out-of-bag error of the random forest and dynamically adjusts the parameters of the Gaussian process kernel function, such as the length scale and signal variance. If the out-of-bag error is high, indicating significant uncertainty in the model prediction, the kernel length scale can be appropriately increased to smooth the model and reduce overfitting. In this way, the Bayesian optimization module can better adapt to the characteristics of the data, improve prediction accuracy and stability, and thus optimize the generation and adjustment of mock rules.

[0052] Step b4: determining the trained decision tree module, the trained random forest module, and the trained Bayesian optimization module as the trained Mock rule prediction model.

[0053] Ultimately, the trained decision tree module, the trained random forest module, and the trained Bayesian optimization module are combined to form a trained mock rule prediction model, which is used to predict the test return results of future mock objects. The decision tree module is used to quickly extract basic rule patterns, the random forest module enhances generalization capabilities to avoid overfitting, and the Bayesian optimization module dynamically adjusts parameter sensitivity. These three modules work together to achieve a balance between high-precision prediction and stability.

[0054] Furthermore, dynamically adjusting the Mock rules of the Mock object based on the predicted optimal return value and the predicted abnormal return rate includes: Step c1: If the predicted optimal return value is not in the return value of the Mock rule, then the predicted optimal return value is added and the usage weights of the return values ​​are redistributed.

[0055] Here, the training of the Mock rule prediction model is run regularly, and the optimal return value of the optimal Mock object of each external dependency is recalculated. If the predicted optimal return value is not in the return value of the Mock rule of the Mock object, the predicted optimal return value is added to the return value of the Mock rule of the Mock object, and the usage weights are reallocated to the return values ​​of the Mock rule of the Mock object. Among them, the usage weight is the probability that each return scenario is randomly selected by the Mock object. When the same dependency call may correspond to multiple different return scenarios, we assign a usage weight to each scenario to avoid the problem of reduced test coverage and authenticity if only a single data is returned when the calling frequency of various data scenarios changes in real business scenarios. The use of weights includes reflecting the real distribution: if the real system has a 70% probability of calling return value 1 and a 30% probability of calling return value 2, the weights are set to 0.7 / 0.3, making the return data of the mock object closer to the production environment; improving test diversity: different weight combinations can drive test cases to cover more scenarios, such as search interfaces, combined queries, etc.; dynamic adaptation: as business hotspots change (for example, the number of calls for return value 2 increases), the system automatically adjusts the weights to quickly incorporate new hotspots into the test focus. For example, in the past, "orderRepository.findById(2)" returned {id: 2, name: "Phone", quantity: 5} more than 90% of the time; but recently, the call frequency of findById(1) has increased, indicating that the proportion of different data in the real business has changed.

[0056] The Mock rules before optimization are: “orderRepository: findById: defaultReturn: { id: 2, name: "Phone", quantity: 5} orderRepository: findById: defaultReturn: { id: 2, name: "Phone", quantity: 5}".

[0057] The optimized Mock rules can be expressed as: “orderRepository: findById: defaultReturn: - { id: 1, name: "Laptop", quantity: 10, weight: 0.7} - { id: 2, name: "Phone", quantity: 5, weight: 0.3}".

[0058] Dynamically calculate weights based on historical return data, support adaptability to new data, and ensure that the adjusted Mock rules are closer to the actual business distribution. Step c2: if the predicted abnormal return rate is greater than the first abnormal return rate threshold and less than or equal to the second abnormal return rate threshold, then reduce the usage weight of the predicted optimal return value.

[0059] Here, when the model predicts a high predicted exception return rate (Perr), it means that the current mock rule is likely to produce an exception (or not meet expectations) in the upcoming call scenario. This usually indicates that "the rule does not match the real business scenario" or "the test input exceeds the rule design range." In this case, the predicted exception return rate can be used to determine how to adjust the mock rule.

[0060] In an embodiment of the present application, if the predicted exception return rate is greater than the first exception return rate threshold and less than or equal to the second exception return rate threshold: for Mock rules configured with exception responses (such as database mocks): reduce the usage weight of the predicted optimal return value; for Mock rules not configured with exception responses (such as HTTP APIs, message queue mocks): the exception return rate is regarded as 0, and the weight is adjusted only according to the call frequency.

[0061] Specifically, when the predicted abnormal return rate exceeds the set first abnormal return rate threshold, it means that the return value does not match the actual business scenario. By reducing the usage weight, the call of the return value is gradually reduced until it is removed from the return value of the Mock rule to adapt to changes in the actual business scenario.

[0062] Furthermore, candidate rules can be generated for the return value and A / B testing can be used to modify incorrect responses into valid responses. Specifically, when the production version of a mock rule's return value is marked as "low confidence," multiple candidate mock rule return value versions can be generated in parallel and the best one selected through A / B testing. First, candidate rules are generated. Based on historical call frequency, the weight distribution of each return value is slightly adjusted (for example, adjusting the weight of id=1 from 0.7 to 0.6 or 0.8, generating one candidate each). For low-frequency or highly abnormal scenarios, attempts are made to remove or merge them to construct "reduced" or "enhanced" rule versions. If a new uncovered scenario (such as a new status code) appears in the log, a candidate rule is generated that includes that scenario. Then, online A / B traffic diversion is performed, randomly assigning test requests to candidate rule groups (A, B, C, etc.) to ensure that traffic statistics for each group are available. Metrics such as the abnormal return rate, test case pass rate, and coverage of each group are monitored. Based on the preset "winning conditions" (such as lowest anomaly rate, highest coverage, and minimum divergence), the best candidate is selected after a certain testing cycle, put online, and archived; unqualified candidates are automatically eliminated to ensure that the final replaced rule is the best version verified by actual testing, so as to modify the incorrect response into a valid response.

[0063] Step c3: If the predicted abnormal return rate is greater than the second abnormal return rate threshold, and the Mock rule contains an abnormal response configuration, then the Mock rule is rolled back to the previous version. Here, if the predicted exception return rate is greater than the second exception return rate threshold: for the Mock rule configured with exception response: trigger rule rollback; for the Mock rule not configured with exception response: skip rollback judgment and only record the exception log.

[0064] For example, in this embodiment of the present application, the first abnormal return rate threshold is set at 10%, and the second abnormal return rate threshold is set at 15%. These thresholds are determined by analyzing the abnormal distribution of normal business scenarios in historical test data. The 90th percentile value of the normal distribution is used as the first threshold, and the maximum value plus two standard deviations is used as the second threshold.

[0065] If the predicted exception return rate exceeds the second exception return rate threshold, it indicates that the mock rules significantly mismatch the exception distribution of the real business. In this case, the mock rules for the mock object need to be rolled back to the last stable version. For example, in an API call scenario, "restTemplate.getForObject("https: / / api.example.com / order / {id}")" used to return the normal value "HTTP 200" 95% of the time, but recently 20% of requests have returned the abnormal value "HTTP 500". The current rule is predicted to result in a 20% probability of returning an abnormal value, exceeding the second exception return rate threshold of 15%. This could seriously affect the passing of most test cases, so the mock rules need to be rolled back to the last stable version.

[0066] The Mock rules before optimization are: “restTemplate: getForObject: defaultReturn: { status: "error", message: "API Failure"}". The default return simulated here is always an "error" response.

[0067] The optimized Mock rules can be expressed as: “restTemplate: getForObject: defaultReturn: { status: "success", data: { id: 1, name: "Laptop"}} rollbackOnFailureRate: 15% # If the exception rate is higher than 15%, automatically roll back to the last stable rule.

[0068] In this way, when the abnormal return rate of the Mock rule return value exceeds the preset second abnormal return rate threshold, a rollback can be automatically triggered to ensure that the test data remains stable and close to the business logic.

[0069] Furthermore, dependency information of each external dependency of the target program to be tested is extracted from the target program to be tested according to the following steps: Step d1: converting the source code file of the target program into an abstract syntax tree.

[0070] Here, we use Eclipse JDT (Java Development Tools) as the core static code parsing tool. Eclipse JDT parses the target program's source code files into an Abstract Syntax Tree (AST). This tree structure comprehensively and accurately reflects all language constructs in the source code (such as classes, methods, variables, and comments).

[0071] First, all source code files of the target program are loaded, formatted, and standardized. Specifically, all ".java" files in the code base are loaded into memory, a file list is created, and basic metadata (such as file name, file path, and last modification time) is recorded. The loaded source files are formatted to ensure uniformity in comments, variable names, and code style. This eliminates parsing errors that may be caused by non-standard code formatting. A unified encoding format (such as UTF-8) and a unified line break standard are applied to all files to ensure that no information is lost due to encoding issues during subsequent parsing.

[0072] Next, we used Eclipse JDT to convert each preprocessed ".java" file into a corresponding AST. The AST is a tree-like structure, with each node corresponding to a syntactic element in the code, such as a class definition, method call, or variable declaration. Specifically, we called the JDT parsing API, passed the source code to the parser, retrieved the root node, and then recursively traversed the entire tree structure.

[0073] In addition, according to actual needs, it can also be supplemented with other parsing libraries (such as Spoon) to ensure that key information is not missed in special syntax or third-party library calls.

[0074] Step d2: traverse all method call nodes, variable declaration nodes, and reference nodes in the abstract syntax tree, and filter out target nodes containing external dependency keywords in identifiers, method names, or method calls from each node.

[0075] Here, we use a traversal method based on the Visitor Pattern to traverse all method call nodes, variable declarations, and reference nodes in the AST, identifying key methods that call external dependencies, such as external database interfaces, HTTP request methods, or message queue-related methods. We pay special attention to object instances in dependency injection (DI) scenarios, capturing dependent objects injected through constructors or "setter" methods to distinguish between direct dependencies and dynamic dependencies. We then filter out target nodes from each node whose identifiers, method names, or method calls contain the external dependency keyword.

[0076] Specifically, for database dependencies, focus on finding whether the identifiers and method names contain database-dependent keywords such as "Repository", "DAO", "EntityManager", "JdbcTemplate", "DataSource", and check whether there are calls to database query methods in the code, such as "findById", "query", "executeQuery", etc.

[0077] For HTTP API dependencies, check whether calls to classes such as "RestTemplate," "HttpClient," and "FeignClient" appear in method calls, and check whether method call parameters contain URL strings, such as strings starting with "http: / / " or "https: / / ."

[0078] For message queue dependencies, look for calls involving interfaces or classes such as "KafkaProducer," "KafkaConsumer," "RabbitTemplate," and "JmsTemplate." Also check whether method calls contain parameters related to message topics or message sending. Step d3: extracting dependency information of each external dependency of the target program according to the target node.

[0079] Here, based on the identified target node, the dependency object name, call location, dependency type, and key parameter information are recorded for each identified external dependency from the corresponding code, and the dependency information of each external dependency of the target program is extracted. Among them, the dependency object name is the name of the external dependency, such as "orderRepository", "restTemplate", "kafkaTemplate", etc.; the call location records the specific call location of the external dependency, including the class, method name, and code line number or code segment range; the dependency type is the dependency type of the external dependency, clearly marked as "database dependency", "HTTP API dependency", or "message queue dependency"; the key parameter information includes the key parameters when the external dependency method is called (such as URL, query conditions, etc.), as well as the call context of the external dependency (such as dependency injection method).

[0080] Furthermore, for each identified external dependency, its information is constructed into structured data (such as a JSON object) while traversing the AST. This data is stored in a temporary data structure in real time and will be output later after being sorted.

[0081] Furthermore, the dependency information of all external dependencies can be integrated to generate a unified dependency mapping table for subsequent module calls. Specifically, all recorded dependency information is summarized, duplicate and redundant data is checked, and data redundancy processing is performed. A dependency mapping table is formed, in which each entry includes: Basic metadata: dependent object name, type, call location, and key parameter information.

[0082] Mock configuration: generation rules (such as exception triggering conditions), predefined data templates (such as return value structure).

[0083] Output the mapping table into a unified format (such as JSON, XML, or key-value pair format) and save it to a database (such as Redis) to facilitate quick query and dynamic update by subsequent modules.

[0084] Furthermore, the dependency information includes the dependency object name, call location, dependency type, and key parameter information; the method further includes: Step e1: monitoring the source code file of the target program.

[0085] Here, the embodiment of the present application can automatically detect code modifications related to Mock objects by monitoring changes in the Git code library. Specifically, when the code involves changes in Mock objects and Mock rules of Mock objects, the corresponding Mock objects or Mock rules are automatically updated according to the latest code logic to ensure that the Mock objects are always synchronized with the latest business logic. This process helps ensure that after each code update, the Mock objects and behaviors in the test environment can reflect the real business scenarios. First, monitor the source code files of the target program.

[0086] Specifically, listen to Git commit changes, use Git Hook (such as post-commit or pre-push) to automatically detect the most recently submitted Java code changes, and obtain the list of affected ".java" files through "git diff". In an embodiment of the present application, a trigger script is added to the Git Hook to automatically detect the Java code changes submitted by Git for the most recent time. Use gitdiff to parse the code differences between the current submission and the previous submission, and extract the list of affected ".java" files. Execute the command ":git diff --name-only HEAD~1 HEAD | grep ".java"" to parse the output and obtain all Java source files that have changed. For example: "src / main / java / com / example / service / OrderService.java". Step e2: If the source code file of the target program is changed, based on the changed source code file, determine whether the dependent object name, call location, dependency type and key parameter information of each external dependency are changed.

[0087] Here, use tools such as Eclipse JDT or Spoon to parse the affected Java files, extract the modified methods, and determine whether the dependent object names, call locations, dependency types, and key parameter information of each external dependency have changed. For example, if a modification is detected for the "findOrderById" method in "OrderService," analyze the method's dependency, "orderRepository.findById."

[0088] Step e3: If yes, for any changed external dependency, determine a Mock object of the external dependency and a Mock rule of the Mock object based on the dependency information of the changed external dependency.

[0089] Here, if it is detected that the dependency object name, call location, dependency type or key parameter information of the external dependency has changed, the Mock object of the external dependency and the Mock rule of the Mock object are determined based on the changed dependency information.

[0090] For example, if you modify the "orderRepository.findById(int id)" method to "findById(String id)" during a code update, the parameter type changes from "int" to "String". In this case, the mock rules need to be automatically adjusted to match the new method signature to avoid test failures.

[0091] Specifically, for this scenario, after monitoring Git commits, we detect signature changes to the "orderRepository.findById" method and record the new method signature, "findById(String id)." Using a static analysis tool (EclipseJDT), we identify changes in method parameter types. Upon detecting the "int→String" change, we automatically update the data type of "id" in the mock rule. Furthermore, to support mock rule rollbacks, we can also implement version number management, recording multiple historical versions to prevent incorrect updates from impacting testing. The pre-optimized mock rule can be represented as: “orderRepository: findById: defaultReturn: { id: 1, name: "Laptop", quantity: 10}".

[0092] The optimized Mock rules can be expressed as: “orderRepository: findById: versions: - { version: "1.0", defaultReturn: { id: 1, name: "Laptop"}} - { version: "1.1", defaultReturn: { id: 1, name: "Laptop", discount:10}} activeVersion: "1.1" # Allow dynamic version switching".

[0093] For example, in a testing scenario involving an API change, a developer might modify the return value of restTemplate.getForObject("https: / / api.example.com / order / {id}") by adding a new field called "discountPrice." The mock rules must be updated to match the new API response structure.

[0094] Specifically, for this scenario, after Git commits are made, the return value structure of the Order object is checked for changes. If a new "discountPrice" field is found, a mock rule update is triggered. The return value after the API change is parsed to extract the newly added field. The mock rule is automatically updated to ensure that the returned JSON structure is consistent with the latest API. The mock rule before optimization can be expressed as: “restTemplate: getForObject: defaultReturn: { status: "success", data: { id: 1, name: "Laptop"}}".

[0095] The optimized Mock rules can be expressed as: “restTemplate: getForObject: defaultReturn: { status: "success", data: { id: 1, name: "Laptop",discountPrice: 99.99}}".

[0096] Furthermore, the method further comprises: Step f1: construct a dependency mapping table of the target program according to the dependency information of each external dependency of the target program; the dependency mapping table includes the dependency information of each external dependency and the mock rules of the mock objects corresponding to each external dependency.

[0097] Here, automatically generated mock objects are integrated with external dependency information to establish a unified mapping relationship. A dynamic configuration interface is provided to adjust mock behavior in real time during testing, meeting ever-changing testing requirements and ensuring that returned data matches business logic. Dependency information corresponds to the basic metadata in the mapping table (including the dependent object name, type, call location, and key parameter information), while mock rules correspond to the mock configuration in the mapping table (including generation rules and predefined data templates). The two are linked through a hierarchical data structure.

[0098] First, traverse the dependency information of the external dependencies obtained in S101, create a mapping entry for each external dependency, and save the mapping table through a data structure (such as JSON format) and store it in the data In the library, define the configuration structure in JSON or YAML format, allowing users to modify the return data, exception strategy, etc. of the Mock object.

[0099] Specifically, using the dependency information of all external dependencies obtained in S101, a mapping entry is created for each external dependency. The entry contains: Basic metadata: Dependent object names: for example, "orderRepository", "restTemplate", and "kafkaTemplate"; Dependency type: database dependency / HTTP API dependency / message queue dependency; Call location: class name + method name (such as "OrderService.getOrderById"); Key parameter information: such as URL path, query conditions, and message subject.

[0100] Mock configuration: Generate rules: exception trigger threshold (such as "throw an exception when the parameter is null").

[0101] Predefined data templates: Database dependency: "Order(1, \"Laptop\", 10)".

[0102] HTTP API dependency: "{ \"status\": \"success\", \"data\": {\"id\": 1}}".

[0103] Message queue dependency: "Message sent to order-topic successfully".

[0104] Example JSON structure: "{ "orderRepository": { "metadata": { "type": "Database dependency", "location": "OrderService.findOrderById()", "keyParams": { "queryMethod": "findById", "paramType": "String", "requiredFields": ["id", "name"], "constraints": { "minLength": 1, "maxLength": 36} } }, "mockConfig": { "rules": { "defaultReturn": { "id": 1, "name": "Laptop"}, "exceptions": { "nullParam": "throw IllegalArgumentException"} } } } } ”.

[0105] Step f2: In response to the adjustment operation of the Mock rule for any Mock object in the dependency mapping table, obtaining the updated Mock rule of the Mock object.

[0106] The embodiments of this application design a set of configuration interfaces that enable users to define and modify the mock behavior of each dependency in real time through external configuration files (such as JSON or YAML format). Configuration items typically include return data, exception policies, response delays, etc. First, define the configuration file structure to ensure that all adjustable parameters are included in the mapping entry for each dependency. Write a configuration management service that loads the configuration file at system startup and monitors file changes at runtime (or performs online configuration modifications through the management platform). When the configuration is modified, the configuration management service automatically updates the internal mapping table and notifies the mock object generation module to update its policy. The configuration management service supports RESTful APIs, allowing testers to submit configuration modification requests online for immediate effect. The configuration interface must support online dynamic modification and immediately apply new mock policies to the system. The system monitors the status of the configuration file regularly or in real time, automatically reloads it when a configuration change is detected, and updates all related modules. In other words, in response to the adjustment operation of the mock rules for any mock object in the dependency mapping table, the updated mock rules for the mock object are obtained.

[0107] Specifically, a file monitoring mechanism is implemented in the configuration management service (such as using the Java WatchService API), which automatically triggers reloading when a file changes. The latest configuration data is updated to the internal mapping table, and the Mock rules for the Mock object are notified to reconfigure through the message queue or event notification mechanism. The configuration data is read to ensure that the latest configuration is used each time a Mock object is generated. For example, when the test feedback indicates that the returned data of an HTTP API Mock object has a large deviation, the tester can modify the configuration items in the YAML file online, such as adjusting the returned JSON data structure. After the configuration management service detects the change, it immediately updates the Mock rules of the HTTP API Mock object in the dependency mapping table, and all subsequent calls to the HTTP API Mock use the new configuration to return data.

[0108] The present application provides a method for adjusting a Mock object, comprising: extracting dependency information of each external dependency of a target program from a target program to be tested; for any external dependency, determining the Mock object of the external dependency and the Mock rule of the Mock object based on the dependency information of the external dependency; for any Mock object, based on the Mock rule of the Mock object, performing a call test on the Mock object to obtain the current test return result of the Mock object; dynamically adjusting the Mock rule of the Mock object based on the current test return result, historical test return result and Mock rule prediction model of the Mock object. In this way, the Mock rule is dynamically adjusted by combining the current and historical test return results of the Mock object through the Mock rule prediction model, thereby improving the adjustment efficiency of the Mock object in the automated test.

[0109] Based on the same application concept, the embodiments of the present application also provide a device for adjusting a Mock object corresponding to the method for adjusting a Mock object provided in the above embodiments. Since the principle of solving the problem by the device in the embodiments of the present application is similar to the method for adjusting a Mock object in the above embodiments of the present application, the implementation of the device can refer to the implementation of the method, and the repeated parts will not be repeated.

[0110] See also Figure 2 , Figure 2 This is one of the functional module diagrams of a Mock object adjustment device provided in an embodiment of the present application. Figure 2 As shown, the Mock object adjustment device 200 includes: The data acquisition module 210 is configured to extract dependency information of each external dependency of the target program from the target program to be tested.

[0111] The rule determination module 220 is configured to determine, for any of the external dependencies, a mock object of the external dependency and a mock rule of the mock object based on the dependency information of the external dependency.

[0112] The test execution module 230 is configured to perform a call test on any of the Mock objects based on the Mock rules of the Mock object, and obtain a current test return result of the Mock object.

[0113] The rule adjustment module 240 is used to dynamically adjust the Mock rules of the Mock object based on the current test return result, historical test return results and the Mock rule prediction model of the Mock object.

[0114] Furthermore, when the rule adjustment module 240 is used to dynamically adjust the Mock rules of the Mock object based on the current test return result, the historical test return result and the Mock rule prediction model of the Mock object, the rule adjustment module 240 is specifically used to: Determine the current input features and historical input features of the Mock object based on the current test return results and historical test return results of the Mock object; wherein the historical input features include an abnormal frequency matrix, a time decay factor, and a rule stability index; Training the Mock rule prediction model based on the historical input features of the Mock object to obtain a trained Mock rule prediction model; Input the current input features of the Mock object into the trained Mock rule prediction model to obtain the predicted optimal return value and predicted abnormal return rate of the Mock object; the predicted abnormal return rate is generated by analyzing the abnormal frequency matrix; Based on the predicted optimal return value and the predicted abnormal return rate of the Mock object, the Mock rules of the Mock object are dynamically adjusted.

[0115] Furthermore, the mock rule prediction model includes a decision tree module, a random forest module, and a Bayesian optimization module; when the rule adjustment module 240 is used to train the mock rule prediction model based on the historical input features of the mock object to obtain a trained mock rule prediction model, the rule adjustment module 240 is specifically used to: Training the decision tree module based on the historical input features of the Mock object to obtain a trained decision tree module and generate a preliminary prediction result of the Mock object; the preliminary prediction result includes a preliminary predicted return value and a preliminary predicted abnormal return rate of the Mock object; The random forest module is trained based on the preliminary prediction results of the mock object to obtain a trained random forest module and generate an optimized prediction result of the mock object; the optimized prediction result includes the optimized prediction return value and the optimized prediction abnormal return rate of the mock object; the output node of the decision tree module is connected with the feature sampler of the random forest module through a probabilistic coupling; The Bayesian optimization module is trained based on the optimization prediction result to obtain a trained Bayesian optimization module; the Bayesian optimization module includes a prior distribution correction unit for adjusting the Gaussian process kernel function according to the out-of-bag error of the random forest module; The trained decision tree module, the trained random forest module, and the trained Bayesian optimization module are determined as the trained Mock rule prediction model. Further, when the rule adjustment module 240 is used to dynamically adjust the Mock rule of the Mock object based on the predicted optimal return value and the predicted abnormal return rate, the rule adjustment module 240 is specifically used to: If the predicted optimal return value is not included in the return value of the Mock rule, then add the predicted optimal return value and redistribute the usage weights of the return values; If the predicted abnormal return rate is greater than the first abnormal return rate threshold and less than or equal to the second abnormal return rate threshold, reducing the usage weight of the predicted optimal return value; If the predicted exception return rate is greater than a second exception return rate threshold, and the Mock rule includes an exception response configuration, the Mock rule is rolled back to a previous version.

[0116] Furthermore, the data acquisition module 210 is configured to extract dependency information of each external dependency of the target program from the target program to be tested according to the following steps: Converting the source code file of the target program into an abstract syntax tree; Traversing all method call nodes, variable declaration nodes, and reference nodes in the abstract syntax tree, and filtering out target nodes whose identifiers, method names, or method calls contain external dependency keywords from each node; Dependency information of each external dependency of the target program is extracted according to the target node.

[0117] Further, see Figure 3 , Figure 3 This is the second functional module diagram of a Mock object adjustment device provided in an embodiment of the present application. The dependency information includes the name of the dependent object, the calling location, the dependency type and the key parameter information; Figure 3 As shown, the Mock object adjustment device 200 further includes: A change monitoring module 250 is used to monitor the source code file of the target program; A change determination module 260 is configured to determine, if the source code file of the target program is changed, whether the dependent object name, call location, dependency type, and key parameter information of each external dependency have changed based on the changed source code file; The change determination module 270 is configured to determine, for any changed external dependency, a Mock object of the external dependency and a Mock rule of the Mock object based on the dependency information of the changed external dependency.

[0118] Furthermore, if Figure 3 As shown, the Mock object adjustment device 200 further includes: A dependency mapping module 280 is configured to construct a dependency mapping table of the target program based on dependency information of each external dependency of the target program; the dependency mapping table includes dependency information of each external dependency and a mock rule of a mock object corresponding to each external dependency; The manual adjustment module 290 is configured to obtain updated Mock rules of any Mock object in the dependency mapping table in response to an adjustment operation on the Mock rules of the Mock object.

[0119] The present application provides an adjustment device for a Mock object, comprising: a data acquisition module for extracting dependency information of each external dependency of a target program from a target program to be tested; a rule determination module for determining, for any external dependency, a Mock object of the external dependency and a Mock rule of the Mock object based on the dependency information of the external dependency; a test execution module for calling a test on the Mock object based on the Mock rule of the Mock object for any Mock object, and obtaining the current test return result of the Mock object; a rule adjustment module for dynamically adjusting the Mock rule of the Mock object based on the current test return result, historical test return result and Mock rule prediction model of the Mock object. In this way, the Mock rule is adjusted by combining the current and historical test return results of the Mock object through the Mock rule prediction model, thereby improving the adjustment efficiency of the Mock object in the automated test.

[0120] Based on the same application idea, please refer to Figure 4 , Figure 4 This is a schematic diagram of the structure of an electronic device provided in an embodiment of the present application. Figure 4 As shown, the electronic device 400 includes a processor 410 , a memory 420 and a bus 430 .

[0121] The memory 420 stores machine-readable instructions executable by the processor 410. When the electronic device 400 is running, the processor 410 communicates with the memory 420 through the bus 430. The machine-readable instructions are executed by the processor 410 to execute the steps of the Mock object adjustment method provided in the above embodiment. The specific implementation method can be found in the method embodiment and will not be repeated here.

[0122] Based on the same application concept, an embodiment of the present application further provides a computer-readable storage medium, on which a computer program is stored. When the computer program is executed by a processor, the steps of the method for adjusting the Mock object provided in the above embodiment are executed. The specific implementation method can be found in the method embodiment and will not be repeated here.

[0123] Those skilled in the art will clearly understand that, for the convenience and brevity of description, the specific working processes of the above-described devices and units can refer to the corresponding processes in the aforementioned method embodiments and will not be repeated here.

[0124] In the embodiments provided in this application, it should be understood that the disclosed devices and methods can be implemented in other ways. The device embodiments described above are merely schematic. For example, the division of the units is only a logical function division. There may be other division methods in actual implementation. For example, multiple units or components can be combined or integrated into another system, or some features can be ignored or not executed. Another point is that the mutual coupling or direct coupling or communication connection shown or discussed can be through some communication interface, indirect coupling or communication connection of devices or units, which can be electrical, mechanical or other forms.

[0125] The units described as separate components may or may not be physically separate, and the components shown as units may or may not be physical units, that is, they may be located in one place or distributed across multiple network units. Some or all of these units may be selected to achieve the purpose of this embodiment according to actual needs.

[0126] In addition, each functional unit in the embodiments provided in the present application may be integrated into one processing unit, or each unit may exist physically separately, or two or more units may be integrated into one unit.

[0127] If the functions are implemented in the form of software functional units and sold or used as independent products, they can be stored in a computer-readable storage medium. Based on this understanding, the technical solution of the present application, or the part that contributes to the prior art, or the part of the technical solution, can be embodied in the form of a software product. The computer software product is stored in a storage medium and includes a number of instructions for enabling a computer device (which can be a personal computer, server, or network device, etc.) to execute all or part of the steps of the method described in each embodiment of the present application. The aforementioned storage medium includes: U disk, mobile hard disk, read-only memory (ROM, Read-Only Memory), random access memory (RAM, Random Access Memory), disk or optical disk, and other media that can store program code.

[0128] It should be noted that similar numbers and letters represent similar items in the following figures. Therefore, once an item is defined in one figure, it does not need to be further defined and explained in subsequent figures. In addition, the terms "first", "second", "third", etc. are only used to distinguish the description and are not to be understood as indicating or implying relative importance.

[0129] Finally, it should be noted that the above-described embodiments are only specific implementation methods of the present application, which are used to illustrate the technical solutions of the present application, rather than to limit them. The scope of protection of the present application is not limited thereto. Although the present application has been described in detail with reference to the above-described embodiments, those skilled in the art should understand that any person skilled in the art can modify or easily conceive of changes to the technical solutions described in the above-described embodiments within the technical scope disclosed in the present application, or make equivalent replacements for some of the technical features thereof. However, these modifications, changes, or replacements do not deviate from the spirit and scope of the technical solutions of the embodiments of the present application. They should all be included in the scope of protection of the present application. Therefore, the scope of protection of the present application should be based on the scope of protection of the claims.

Claims

1. A method for adjusting a Mock object, characterized in that: The method comprises: Extracting dependency information of each external dependency of the target program from the target program to be tested; For any of the external dependencies, determining a mock object of the external dependency and a mock rule of the mock object based on the dependency information of the external dependency; For any of the Mock objects, based on the Mock rules of the Mock object, call the Mock object for testing and obtain the current test return result of the Mock object; Based on the current test return result, historical test return result and Mock rule prediction model of the Mock object, the Mock rules of the Mock object are dynamically adjusted.

2. The method for adjusting a Mock object according to claim 1, wherein: The dynamically adjusting the Mock rules of the Mock object based on the current test return result, the historical test return result and the Mock rule prediction model of the Mock object includes: Determine the current input features and historical input features of the Mock object based on the current test return results and historical test return results of the Mock object; wherein the historical input features include an abnormal frequency matrix, a time decay factor, and a rule stability index; Training the Mock rule prediction model based on the historical input features of the Mock object to obtain a trained Mock rule prediction model; Input the current input features of the Mock object into the trained Mock rule prediction model to obtain the predicted optimal return value and predicted abnormal return rate of the Mock object; the predicted abnormal return rate is generated by analyzing the abnormal frequency matrix; Based on the predicted optimal return value and the predicted abnormal return rate of the Mock object, the Mock rules of the Mock object are dynamically adjusted.

3. The method for adjusting a Mock object according to claim 2, wherein: The Mock rule prediction model includes a decision tree module, a random forest module, and a Bayesian optimization module; the Mock rule prediction model is trained based on the historical input features of the Mock object to obtain a trained Mock rule prediction model, including: Training the decision tree module based on the historical input features of the Mock object to obtain a trained decision tree module and generate a preliminary prediction result of the Mock object; the preliminary prediction result includes a preliminary predicted return value and a preliminary predicted abnormal return rate of the Mock object; The random forest module is trained based on the preliminary prediction results of the mock object to obtain a trained random forest module and generate an optimized prediction result of the mock object; the optimized prediction result includes the optimized prediction return value and the optimized prediction abnormal return rate of the mock object; the output node of the decision tree module is connected with the feature sampler of the random forest module through a probabilistic coupling; The Bayesian optimization module is trained based on the optimization prediction result to obtain a trained Bayesian optimization module; the Bayesian optimization module includes a prior distribution correction unit for adjusting the Gaussian process kernel function according to the out-of-bag error of the random forest module; The trained decision tree module, the trained random forest module and the trained Bayesian optimization module are determined as the trained Mock rule prediction model.

4. The method for adjusting a Mock object according to claim 2, wherein: The dynamically adjusting the Mock rules of the Mock object based on the predicted optimal return value and the predicted abnormal return rate includes: If the predicted optimal return value is not included in the return value of the Mock rule, then add the predicted optimal return value and redistribute the usage weights of the return values; If the predicted abnormal return rate is greater than the first abnormal return rate threshold and less than or equal to the second abnormal return rate threshold, reducing the usage weight of the predicted optimal return value; If the predicted exception return rate is greater than a second exception return rate threshold, and the Mock rule includes an exception response configuration, the Mock rule is rolled back to a previous version.

5. The method for adjusting a Mock object according to claim 1, wherein: Extract dependency information of each external dependency of the target program from the target program to be tested according to the following steps: Converting the source code file of the target program into an abstract syntax tree; Traversing all method call nodes, variable declaration nodes, and reference nodes in the abstract syntax tree, and filtering out target nodes whose identifiers, method names, or method calls contain external dependency keywords from each node; Dependency information of each external dependency of the target program is extracted according to the target node.

6. The method for adjusting a Mock object according to claim 5, wherein: The dependency information includes the name of the dependent object, the calling location, the dependency type and key parameter information; the method further includes: Monitoring the source code file of the target program; If the source code file of the target program is changed, based on the changed source code file, determining whether the dependent object name, call location, dependency type, and key parameter information of each external dependency have changed; If so, for any changed external dependency, based on the changed dependency information of the external dependency, determine a Mock object of the external dependency and a Mock rule of the Mock object.

7. The method for adjusting a Mock object according to claim 6, wherein: The method further comprises: Constructing a dependency mapping table of the target program according to the dependency information of each external dependency of the target program; the dependency mapping table includes the dependency information of each external dependency and the mock rules of the mock objects corresponding to each external dependency; In response to the adjustment operation on the Mock rule of any Mock object in the dependency mapping table, an updated Mock rule of the Mock object is obtained.

8. A device for adjusting a mock object, characterized in that: The adjustment device of the Mock object includes: A data acquisition module, configured to extract dependency information of each external dependency of a target program to be tested from the target program to be tested; A rule determination module is used to determine, for any of the external dependencies, a mock object of the external dependency and a mock rule of the mock object based on the dependency information of the external dependency; A test execution module is used to call and test any of the Mock objects based on the Mock rules of the Mock object, and obtain the current test return result of the Mock object; The rule adjustment module is used to dynamically adjust the Mock rules of the Mock object based on the current test return result of the Mock object, the historical test return result and the Mock rule prediction model.

9. An electronic device, characterized in that: include: A processor, a memory, and a bus, wherein the memory stores machine-readable instructions executable by the processor. When the electronic device is running, the processor and the memory communicate via the bus. When the machine-readable instructions are run by the processor, the steps of the method for adjusting a mock object as described in any one of claims 1 to 7 are executed.

10. A computer-readable storage medium, characterized in that The computer-readable storage medium stores a computer program, and when the computer program is executed by a processor, the steps of the method for adjusting a mock object according to any one of claims 1 to 7 are executed.

Citation Information

Patent Citations

  • Method and device for automatic mock of external dependency

    CN105335281A

  • Mock test method and device, electronic equipment and computer readable storage medium

    CN112131118A

  • Dependent resource compatibility testing method and device, equipment and medium

    CN120104503A

  • Unified unit and integration test with automatic mock creation

    US8627296B1