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

By combining the current and historical test results of the Mock object, the Mock rules are dynamically adjusted using the Mock rule prediction model, which solves the problem of low adjustment efficiency of the Mock object in the existing technology, realizes the adaptive and efficient simulation of the Mock object in the test environment, and improves the stability and accuracy of automated testing.

CN120705057BActive Publication Date: 2025-12-16北京领雁科技股份有限公司
View PDF 2 Cites 0 Cited by

Patent Information

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

AI Technical Summary

Technical Problem

Existing methods for adjusting Mock objects are difficult to adapt to rapid changes in the testing environment and external dependencies, resulting in low efficiency in adjusting Mock objects during automated testing.

Method used

By combining the current and historical test results of the Mock object, the Mock rule prediction model is used to dynamically adjust the Mock rules, thereby improving the adjustment efficiency of the Mock object.

Benefits of technology

It automates and improves the efficiency of Mock object adjustment, ensuring that Mock objects can adaptively simulate the behavior of external dependencies in the test environment, thereby improving the stability and accuracy of testing.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN120705057B_ABST
    Figure CN120705057B_ABST
Patent Text Reader

Abstract

The application provides a Mock object adjustment method and device, an electronic device, and a storage medium. Dependency information of each external dependency of a target program is extracted from a target program to be tested. For any external dependency, a Mock object of the external dependency and a Mock rule of the Mock object are determined based on the dependency information of the external dependency. For any Mock object, the Mock object is called for testing based on the Mock rule of the Mock object, and a current test return result of the Mock object is obtained. The Mock rule of the Mock object is dynamically adjusted based on the current test return result, a historical test return result, and a Mock rule prediction model of the Mock object. In this way, 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 automatic testing is improved.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to the field of automated testing technology, and in particular to methods, apparatus, electronic devices and storage media for adjusting Mock objects. Background Technology

[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 in ensuring software stability and reliability.

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

[0004] However, with the continuous changes in automated testing environments and the dynamic changes in external dependencies, the mock rules of mock objects also need to be frequently updated to ensure the accuracy and consistency of mock object simulation of external dependencies. Existing methods for adjusting mock objects rely on manually writing code to adjust and update mock rules, which is difficult to adapt to the rapid changes in testing environments and external dependencies, resulting in low efficiency in adjusting mock objects in automated testing. Summary of the Invention

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

[0006] This application mainly includes the following aspects:

[0007] In a first aspect, embodiments of this application provide a method for adjusting a Mock object, the method comprising: extracting dependency information of each external dependency of the target program from the target program to be tested; for any external dependency, determining a Mock object and a Mock rule for the external dependency based on the dependency information; for any Mock object, performing a call test on the Mock object based on the Mock rule to obtain the 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, historical test return results, and a Mock rule prediction model.

[0008] Secondly, embodiments of this application also provide a device for adjusting a Mock object, the device comprising: a data acquisition module, configured to extract dependency information of each external dependency of the target program from the target program to be tested; a rule determination module, configured to determine, for any external dependency, a Mock object and a Mock rule of the external dependency based on the dependency information of the external dependency; a test execution module, configured to perform a call test on any Mock object based on the Mock rule of the Mock object, and obtain the current test return result of the Mock object; and a rule adjustment module, configured to dynamically adjust the Mock rule of the Mock object based on the current test return result, historical test return results, and a Mock rule prediction model.

[0009] Thirdly, embodiments of this application also provide an electronic device, including: a processor, a memory, and a bus. The memory stores machine-readable instructions executable by the processor. When the electronic device is running, the processor communicates with the memory through the bus, and the machine-readable instructions are executed by the processor to perform the steps of the adjustment method of the Mock object as described above.

[0010] Fourthly, embodiments of this application also provide a computer-readable storage medium storing a computer program, which, when executed by a processor, performs the steps of the adjustment method for the Mock object as described above.

[0011] The method, apparatus, electronic device, and storage medium for adjusting Mock objects provided in this application extract dependency information of each external dependency of the target program to be tested; for any external dependency, based on the dependency information, determine the Mock object and Mock rules of the external dependency; for any Mock object, based on the Mock rules of the Mock object, perform call tests on the Mock object to obtain the current test return result of the Mock object; and dynamically adjust the Mock rules of the Mock object based on the current test return result, historical test return results, and a Mock rule prediction model. In this way, by combining the current and historical test return results of the Mock object and dynamically adjusting the Mock rules through a Mock rule prediction model, the efficiency of adjusting Mock objects in automated testing is improved.

[0012] To make the above-mentioned objectives, features and advantages of this application more apparent and understandable, preferred embodiments are described below in detail with reference to the accompanying drawings. Attached Figure Description

[0013] To more clearly illustrate the technical solutions of the embodiments of this application, the accompanying drawings used in the embodiments will be briefly introduced below. It should be understood that the following drawings only show some embodiments of this application and should not be regarded as a limitation of the scope. For those skilled in the art, other related drawings can be obtained based on these drawings without creative effort.

[0014] Figure 1 A flowchart illustrating a method for adjusting a Mock object provided in an embodiment of this application is shown;

[0015] Figure 2 This invention provides a functional block diagram of an adjustment device for a Mock object according to an embodiment of the present application.

[0016] Figure 3 This is a second functional block diagram of a Mock object adjustment device provided in an embodiment of this application;

[0017] Figure 4 A schematic diagram of the structure of an electronic device provided in an embodiment of this application is shown. Detailed Implementation

[0018] To make the objectives, technical solutions, and advantages of the embodiments of this application clearer, the technical solutions of the embodiments of this application will be clearly and completely described below with reference to the accompanying drawings. It should be understood that the drawings in this application are for illustrative and descriptive purposes only and are not intended to limit the scope of protection of this application. Furthermore, it should be understood that the schematic drawings are not drawn to scale. The flowcharts used in this application illustrate operations implemented according to some embodiments of this application. It should be understood that the operations in the flowcharts may not be implemented in sequence, and steps without logical contextual relationships may be reversed or implemented simultaneously. In addition, those skilled in the art, guided by the content of this application, may add one or more other operations to the flowcharts, or remove one or more operations from the flowcharts.

[0019] Furthermore, the described embodiments are merely some, not all, of the embodiments of this application. The components of the embodiments of this application described and illustrated herein can typically be arranged and designed in various different configurations. Therefore, the following detailed description of the embodiments of this application provided in the accompanying drawings is not intended to limit the scope of the claimed application, but merely to illustrate selected embodiments of the application. All other embodiments obtained by those skilled in the art based on the embodiments of this application without inventive effort are within the scope of protection of this application.

[0020] To facilitate understanding of this application, the technical solutions provided in this application will be described in detail below with reference to specific embodiments.

[0021] Please see Figure 1 , Figure 1 This is a flowchart illustrating a method for adjusting a Mock object provided in an embodiment of this application. Figure 1 As shown in the embodiments of this application, the method for adjusting a Mock object includes the following steps:

[0022] S101, extract the dependency information of each external dependency of the target program from the target program to be tested.

[0023] Here, static code analysis technology is used to scan the target program's codebase using automated tools (such as Eclipse JDT) to extract dependency information for each external dependency of the target program under test. External dependencies refer to external resources or components that a software project depends on during its operation or construction. These dependencies are typically not part of the project itself, but are provided by third parties or generated by other projects. In this embodiment, the dependency types of external dependencies include at least one of database dependencies, HTTP API dependencies, and message queue dependencies. The dependency information records the type, invocation method, and related parameters of the external dependency, specifically including the name of the dependent object, the invocation location, the dependency type, and key parameter information. By extracting the dependency information of external dependencies, data support can be provided for subsequent generation and adjustment of mock objects.

[0024] S102, for any of the external dependencies, based on the dependency information of the external dependencies, determine the Mock object of the external dependency and the Mock rules of the Mock object.

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

[0026] In this embodiment, a corresponding Mock object is generated for each external dependency according to its dependency information and dependency type. Specifically, external dependencies are categorized into database dependencies, HTTP API dependencies, and message queue dependencies based on their call type, corresponding to database Mock, HTTP API Mock, and message queue Mock, respectively. Methods involving database access operations such as "findById," "query," and "execute" are identified as database dependencies; methods involving HTTP client calls such as "getForObject," "postForObject," and "execute" are identified as HTTP API dependencies; and methods involving message queue operations such as "send" and "publish" are identified as message queue dependencies.

[0027] The predefined mocking rules for the database are as follows: when the call parameters meet expectations, predefined virtual data is returned; when the parameters are abnormal, an exception is simulated or an error status is returned. For example, when the expression "orderRepository.findById(orderId)" is encountered, "orderRepository" is identified as a database dependency. The corresponding predefined mocking rules are: if the parameter equals 1, virtual order data is returned (e.g., Order(1, "Laptop", 10)); if the parameter is null or negative, an exception is simulated.

[0028] Specifically, the predefined rules for database mocking are implemented through the following structured configuration:

[0029] {

[0030] "normalResponse": {

[0031] "condition": "params.id == 1",

[0032] "template": { "id": 1, "name": "Laptop", "quantity": 10}

[0033] },

[0034] "exceptionResponse": {

[0035] "condition": "params.id == null || params.id<0",

[0036] "template": { "type": "OrderNotFoundException", "message": "InvalidID"}

[0037] }

[0038] }".

[0039] The predefined mocking rules for HTTP API Mock are to directly return a JSON data structure with the same format as the actual service response. For example, when calling "restTemplate.getForObject(...)", it is identified as an HTTP API dependency. The corresponding predefined mocking rules for HTTP API Mock are to return a JSON response in the format "{"status":"success","data":{"id":1,"name":"Laptop"}}".

[0040] Specifically, the predefined rules of HTTP API Mock are implemented through the following structured configuration:

[0041] {

[0042] "normalResponse": {

[0043] "condition": "true", / / Returns without conditions

[0044] "template": { "status": "success", "data": { "id": 1, "name": "Laptop"}}

[0045] },

[0046] "exceptionResponse": null / / Undefined exception response

[0047] }".

[0048] The predefined mocking rules for message queues intercept message sending and directly return an acknowledgment message without actually transmitting the message over the network. For example, when calling "kafkaTemplate.send(...)", it identifies a message queue dependency. The corresponding predefined mocking rule for message queues is to return the string "Message sent to order-topics successfully".

[0049] Specifically, the predefined rules of message queue Mock are implemented through the following structured configuration:

[0050] {

[0051] "normalResponse": {

[0052] "condition": "true",

[0053] "template": "Message sent to order-topic successfully"

[0054] },

[0055] "exceptionResponse": null / / Undefined exception response

[0056] }".

[0057] 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 the current test return result of the Mock object.

[0058] Here, for any given mock object, a call test is performed on the mock object based on its mock rules, and the current test return result of the mock object is obtained. Specifically, the mock object intercepts external dependency call information and returns the current test result according to predefined mock rules.

[0059] Specifically, for database mocking, to ensure that no actual database connection is needed during testing, a mock framework is embedded in the system. This intercepts database query calls (such as "findById") to control database query behavior. When a specific query call (such as "orderRepository.findById") is detected, a predefined rule is triggered. According to the predefined rule, if the query parameter is valid, virtual order data is returned directly; if the query parameter is invalid, an exception is simulated or an error status is returned. For example, when "orderRepository.findById(1)" is called, no query is executed, and a virtual order object is returned directly. When "orderRepository.findById(-1)" or "orderRepository.findById(null)" is called, no query is executed, and an exception is simulated, such as "OrderNotFoundException".

[0060] For HTTP API mocking, to ensure that external HTTP requests are not actually made in the test environment, all request calls made through HTTP clients (such as "RestTemplate") are captured in the code and replaced with real calls through an interception mechanism. The method call parameters are checked for the presence of a URL string to determine if the call is an external API request. Based on predefined rules, a JSON data format consistent with the real service response is directly returned. The returned data structure is ensured to include a status identifier, data portion, and necessary metadata to guarantee that test cases can correctly parse the response data. For example, when the external dependency information includes an external API request call "restTemplate.getForObject("https: / / api.example.com / order / 1", Order.class)", the mock object, through the interception mechanism, does not make an actual HTTP request but directly returns the following JSON data: "{ "status": "success", "data": { "id": 1, "name": "Laptop"}}".

[0061] For message queue mocking, to ensure that message sending and receiving in the test environment are simulated by mock objects without actual network transmission, interceptors are used to capture message queue-related calls (such as the "send" method of "KafkaProducer" or "RabbitTemplate") before the call occurs. A set of simulated return values ​​is predefined; when the message sending operation is intercepted, an acknowledgment is returned directly, indicating that the message has been "sent". Furthermore, message consumption scenarios can be simulated as needed, returning corresponding acknowledgment results or simulated message content. For example, when the code calls "kafkaTemplate.send("order-topic", order)", the mock object intercepts the call, does not perform actual message delivery, and directly returns an acknowledgment, such as "Message sent to order-topic successfully".

[0062] S104. Based on the current test return results, historical test return results, and Mock rule prediction model of the Mock object, dynamically adjust the Mock rules of the Mock object.

[0063] Here, based on dependency relationships and the Mock rule prediction model, Mock objects can be dynamically generated and their Mock rules adjusted. This allows Mock objects to not only simulate the behavior of external dependencies but also adaptively adjust their behavior according to changes in business logic. The historical test results of the Mock objects consist of a complete historical dataset collected during test execution, comprising the call parameters, return values, and exception information of the Mock object. This dataset provides a data foundation for training the subsequent Mock rule prediction model. Specifically, obtaining historical test results can be achieved by integrating a log interceptor module into a Mock framework (such as Mockito or WireMock). For each call to the Mock object, the following information is captured and recorded:

[0064] The method name to be called (e.g., "orderRepository.findById");

[0065] Input parameters (e.g., "{ "id": 1}");

[0066] Return value (e.g., "{ "id": 1, "name": "Laptop", "quantity": 10}");

[0067] Abnormal situations (if any abnormality occurs, record the abnormality type and error message);

[0068] When making API calls, additional information such as the request URL and HTTP status code is recorded.

[0069] The above data is categorized and stored, for example, database mocks, HTTP API mocks, and message queue mocks are stored separately. Specifically, Kafka is used for real-time log streaming storage, outputting data from each call in JSON format; Redis is used as a short-term cache to ensure fast data retrieval; and data is stored in Elasticsearch for long-term trend analysis and retrieval. The JSON output can be represented as follows:

[0070] {

[0071] "mockType": "database",

[0072] "method": "orderRepository.findById",

[0073] "input": { "id": 1},

[0074] "output": { "id": 1, "name": "Laptop", "quantity": 10},

[0075] "timestamp": "2025-03-22T10:30:00Z",

[0076] "requestCount": 150,

[0077] "exceptionRate": 0.05}".

[0078] Extended storage fields include "timestamp" (record call time), "requestCount" (cumulative call count), and "exceptionRate" (exception return rate) for subsequent analysis. Finally, the collected log data is cleaned, removing null values, incomplete records, and outliers. All values ​​are normalized, and the JSON structure is standardized to ensure consistent data format. For repeated calls to the same method with identical parameters, deduplication and merging are performed to reduce data redundancy and obtain historical test return results.

[0079] Furthermore, the step of dynamically adjusting the Mock rules of the Mock object based on the current test return results, historical test return results, and the Mock rule prediction model includes:

[0080] Step a1: Based on the current test return results and historical test return results of the Mock object, determine the current input features and historical input features of the Mock object.

[0081] 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:

[0082] API call path (e.g., " / order / {id}");

[0083] Request parameters (e.g., id=1);

[0084] The number of times the same method has been called in the past;

[0085] Historical return data structure (including status codes, return value content, etc.);

[0086] Historical exception return rate (calculated as the proportion of exception calls);

[0087] Time dimension (stability of rules distinguishing between peak and off-peak periods).

[0088] Historical input features also include three types of data:

[0089] Anomaly Frequency Matrix: Records the probability of anomalies occurring under different time periods and parameter combinations in the form of "time period × parameter value". (If a Mock rule does not support anomalies, the corresponding item in this matrix is ​​0); Time Decay Factor: Attenuates older data in the "Anomaly Frequency Matrix" to highlight recent anomaly information. Rule Stability Indicators: Measure the historical reliability of each Mock rule, such as rollback count, anomaly rate fluctuation, and test pass rate. Current Input Features refer to the parameter values ​​and call timestamps used in this test call, used to express the "real-time characteristics of this scenario". For Mock rules without configured anomaly responses (such as HTTP API and message queue Mock), the historical anomaly return rate is fixed at 0 and is not included in the calculation of anomaly rate-related features.

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

[0091] Here, a machine learning model is trained based on the historical input features of the mock object. This allows the trained mock rule prediction model to extract high-frequency patterns from historical mock call records (historical input features), identify the optimal mock return rule for each dependent scenario (current input features), and predict the abnormal return rate of the current rule, providing a basis for subsequent dynamic rule adjustments. In this embodiment, Sklearn or TensorFlow is used to build the training model. The collected historical input features are used as the training set to train the mock rule prediction model to predict the optimal return value and abnormal rate. During model training, cross-validation and anomaly detection algorithms are used to remove abnormal data, ensuring accurate model prediction. The trained model is stored as an updatable model, supporting dynamic querying and real-time updates.

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

[0093] Here, the current input features of the Mock object are input 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 represent the possible optimal return value and the probability of triggering an abnormal return in future calls.

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

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

[0096] Furthermore, the Mock rule prediction model includes a decision tree module, a random forest module, and a Bayesian optimization module; training the Mock rule prediction model based on the historical input features of the Mock object to obtain the trained Mock rule prediction model includes:

[0097] Step b1: Train the decision tree module based on the historical input features of the Mock object to obtain the trained decision tree module and generate the preliminary prediction result of the Mock object; the preliminary prediction result includes the preliminary prediction return value and the preliminary prediction anomaly return rate of the Mock object.

[0098] Here, 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 initial rule learning to identify Mock return patterns under different input parameters. The historical input features of the Mock object are input into the decision tree module for training, resulting in a trained decision tree module that generates preliminary prediction results for the Mock object. The preliminary prediction results include the preliminary predicted return value and the preliminary predicted anomaly return rate of the Mock object.

[0099] Step b2: Train the random forest module based on the preliminary prediction results of the Mock object to obtain the trained random forest module and generate the optimized prediction results of the Mock object; the optimized prediction results include the optimized prediction return value and the optimized prediction anomaly return rate of the Mock object; the output node of the decision tree module establishes a probabilistic coupling connection with the feature sampler of the random forest module.

[0100] Here, a Random Forest model is then used to improve the model's generalization ability and avoid overfitting. The preliminary prediction results of the mock objects are input into the Random Forest module for training, resulting in a trained Random Forest module that generates optimized prediction results for the mock objects. The optimized prediction results include the optimized prediction return value and the optimized prediction anomaly return rate of the mock objects. The output nodes of the decision tree module are probabilistically coupled with the feature samplers of the Random Forest module. 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 model's generalization ability and prediction accuracy.

[0101] Step b3: Train the Bayesian optimization module based on the optimized prediction results to obtain the trained Bayesian optimization module; the Bayesian optimization module includes a prior distribution correction unit, which is used to adjust the Gaussian process kernel function according to the out-of-bag error of the random forest module.

[0102] Here, Bayesian optimization is introduced. By adjusting parameters, the abnormal return rate of the model's predictions is detected and automatically adjusted. The optimized prediction results are then input into the Bayesian optimization module for training, resulting in a trained Bayesian optimization module. This module includes a prior distribution correction unit, used to adjust the Gaussian process kernel function based on the out-of-bag error of the random forest module. Specifically, the prior distribution correction unit dynamically adjusts the parameters of the Gaussian process kernel function, such as the length scale and signal variance, by analyzing the out-of-bag error of the random forest. If the out-of-bag error is high, it indicates greater uncertainty in the model's predictions. In this case, the length scale of the kernel function can be appropriately increased to make the model smoother and reduce overfitting. In this way, the Bayesian optimization module can better adapt to the characteristics of the data, improving the accuracy and stability of predictions, thereby optimizing the generation and adjustment process of mock rules.

[0103] Step b4: The trained decision tree module, the trained random forest module, and the trained Bayesian optimization module are identified as the trained Mock rule prediction model.

[0104] Finally, 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 results of future mock objects. The decision tree module is used to quickly extract basic rule patterns, the random forest module enhances generalization ability and avoids overfitting, and the Bayesian optimization module dynamically adjusts parameter sensitivity. The three work together to achieve a balance between high-precision prediction and stability.

[0105] Furthermore, the step of dynamically adjusting the Mock rules of the Mock object based on the predicted optimal return value and the predicted abnormal return rate includes:

[0106] Step c1: If the predicted optimal return value is not among the return values ​​of the Mock rule, then add the predicted optimal return value and reallocate the usage weights of each return value.

[0107] Here, the training of the Mock rule prediction model is run periodically, and the optimal return value of the optimal Mock object for 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 reassigned to each return value of the Mock rule of the Mock object. The usage weights represent 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 realism if only a single data is returned when the call frequency of various data scenarios changes in real business scenarios. The use of weights serves several purposes: reflecting the true distribution: if the real system calls return value one with a 70% probability and return value two with a 30% probability, the weights are set to 0.7 / 0.3, making the returned 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 and combined queries; and dynamic adaptation: as business hotspots change (e.g., the call volume of return value two increases), the system automatically adjusts the weights, allowing new hotspots to be quickly incorporated 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.

[0108] The original Mock rules were:

[0109] "orderRepository:

[0110] findById:

[0111] defaultReturn: { id: 2, name: "Phone", quantity: 5} orderRepository:

[0112] findById:

[0113] defaultReturn: { id: 2, name: "Phone", quantity: 5}".

[0114] The optimized Mock rules can be expressed as:

[0115] "orderRepository:

[0116] findById:

[0117] defaultReturn:

[0118] - { id: 1, name: "Laptop", quantity: 10, weight: 0.7}

[0119] - { id: 2, name: "Phone", quantity: 5, weight: 0.3}".

[0120] The weights are dynamically calculated based on historical returned data, supporting adaptation to new data and ensuring that the adjusted Mock rules are closer to the actual business distribution.

[0121] Step c2: If the predicted anomaly return rate is greater than the first anomaly return rate threshold and less than or equal to the second anomaly return rate threshold, then reduce the weight of the predicted optimal return value.

[0122] Here, a high prediction anomaly return rate (Perr) indicates a higher likelihood that the current Mock rule will generate anomalies (or fail to meet expectations) in the upcoming call scenario. This typically suggests that "the rule does not match the real business scenario" or "the test input exceeds the scope of the rule design." In this case, the Mock rule should be adjusted based on the magnitude of the prediction anomaly return rate.

[0123] In this embodiment of the application, 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: for Mock rules configured with abnormal response (such as database Mock): reduce the weight of using the predicted optimal return value; for Mock rules without abnormal response (such as HTTP API, message queue Mock): the abnormal return rate is regarded as 0, and the weight is adjusted only according to the call frequency.

[0124] Specifically, when the predicted abnormal return rate exceeds the set first abnormal return rate threshold, it indicates that the return value is not well matched with the actual business scenario. The call to the return value is gradually reduced by lowering the weight of its use until it is removed from the return value of the Mock rule, in order to adapt to the changes in the actual business scenario.

[0125] Furthermore, candidate rules can be generated for this return value, and A / B testing can be used to modify the error response into a valid response. Specifically, when the online 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 can be 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 (e.g., adjusting the weight of id=1 from 0.7 to 0.6 and 0.8 to generate one candidate each). For low-frequency or high-abnormal scenarios, attempts are made to eliminate or merge them, constructing "reduced" or "enhanced" rules. If a new, uncovered scenario appears in the logs (e.g., a new status code), candidate rules containing that scenario are generated. Next, online A / B traffic splitting is performed, randomly assigning test requests to each candidate rule group (A, B, C, etc.) to ensure that the traffic of each group is statistically accountable. The abnormal return rate, test case pass rate, coverage, and other metrics of each group are monitored. Based on preset "winning criteria" (such as lowest anomaly rate, highest coverage, and lowest divergence), the best candidate is selected after a certain testing period, deployed, and archived; unqualified candidates are automatically eliminated to ensure that the final replacement rule is the best version verified by actual testing, so as to modify the error response into a valid response.

[0126] Step c3: If the predicted anomaly return rate is greater than the second anomaly return rate threshold, and the Mock rule contains anomaly response configuration, then the Mock rule is rolled back to the previous version.

[0127] Here, if the predicted abnormal return rate is greater than the second abnormal return rate threshold: for Mock rules configured with abnormal response: trigger rule rollback; for Mock rules without abnormal response: skip rollback judgment and only record abnormal logs.

[0128] For example, in this embodiment of the application, the first abnormal return rate threshold is set to 10%, and the second abnormal return rate threshold is set to 15%. These thresholds are determined by analyzing the abnormal distribution of normal business scenarios in historical test data. The 90th percentile of the normal distribution is taken as the first threshold; the maximum value plus twice the standard deviation is taken as the second threshold.

[0129] Here, if the predicted exception return rate exceeds the second exception return rate threshold, it indicates that the Mock rules are severely inconsistent with the actual exception distribution in the business logic. In this case, the Mock rules for the Mock object need to be rolled back to the previous stable version. For example, in an API call scenario, "restTemplate.getForObject("https: / / api.example.com / order / {id}")" previously returned the normal value "HTTP 200" 95% of the time, but recently 20% of requests have returned the exception value "HTTP 500". It is predicted that the current rule will cause a 20% probability of returning an exception value, exceeding the second exception return rate threshold of 15%, which may seriously affect the passing of most test cases. Therefore, the Mock rules need to be rolled back to the previous stable rule.

[0130] The original Mock rules were:

[0131] restTemplate:

[0132] getForObject:

[0133] The `defaultReturn: { status: "error", message: "API Failure"}` statement simulates an error response.

[0134] The optimized Mock rules can be expressed as:

[0135] restTemplate:

[0136] getForObject:

[0137] defaultReturn: { status: "success", data: { id: 1, name: "Laptop"}}

[0138] rollbackOnFailureRate: 15% # If the failure rate is higher than 15%, automatically roll back to the last stable rule.

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

[0140] Further, the dependency information of each external dependency of the target program is extracted from the target program to be tested according to the following steps:

[0141] Step d1: Convert the source code file of the target program into an abstract syntax tree.

[0142] Here, Eclipse JDT (Java Development Tools) is used as the core static code parsing tool. Eclipse JDT can parse the source code file of the target program into an Abstract Syntax Tree (AST). This tree structure can comprehensively and accurately reflect all language constructs in the source code (such as classes, methods, variables, comments, etc.).

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

[0144] Next, Eclipse JDT is used to convert each preprocessed ".java" file into its corresponding AST. An AST is a tree structure where each node corresponds to a syntactic element in the code, such as a class definition, method call, or variable declaration. Specifically, the parsing API provided by JDT is called, the source code is passed to the parser, the root node is obtained, and then the entire tree structure is recursively traversed.

[0145] In addition, depending on actual needs, other parsing libraries (such as Spoon) can be used to supplement the process to ensure that no key information is missed in special syntax or third-party library calls.

[0146] Step d2 involves 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 the keyword "external dependency".

[0147] Here, a visitor pattern-based traversal approach is adopted, iterating through all method call nodes, variable declaration nodes, and reference nodes in the AST to identify key methods that call external dependencies, such as those calling external database interfaces, HTTP request methods, or message queue-related methods. Special attention is paid to object instances in dependency injection (DI) scenarios, capturing dependency objects injected through constructors or setter methods to distinguish between direct and dynamic dependencies. Next, target nodes containing the keyword "external dependency" in their identifiers, method names, or method calls are selected from each node.

[0148] Specifically, for database dependencies, the focus is on checking whether identifiers and method names contain keywords related to database dependencies such as "Repository", "DAO", "EntityManager", "JdbcTemplate", and "DataSource", and whether there are calls to database query methods in the code, such as "findById", "query", and "executeQuery".

[0149] For HTTP API dependencies, check if the method calls contain calls to classes such as "RestTemplate", "HttpClient", or "FeignClient", and check if the method call parameters contain URL strings, such as strings that start with "http: / / " or "https: / / ".

[0150] For message queue dependencies, look for calls involving interfaces or classes such as "KafkaProducer", "KafkaConsumer", "RabbitTemplate", and "JmsTemplate", and check whether the method calls contain parameters related to message topics or message sending.

[0151] Step d3: Based on the target node, extract the dependency information of each external dependency of the target program.

[0152] Here, based on the identified target nodes, the dependency information of each identified external dependency is extracted from the corresponding code, including the dependency object name, call location, dependency type, and key parameter information. The dependency object name is the name of the external dependency, such as "orderRepository", "restTemplate", or "kafkaTemplate"; the call location records the specific call location of the external dependency, including the class, method name, and line number or code segment range; the dependency type is the dependency type of the external dependency, explicitly marked as "database dependency", "HTTP API dependency", or "message queue dependency"; and the key parameter information includes key parameters when the external dependency method is called (such as URL, query conditions, etc.) and the external dependency's call context (such as dependency injection method).

[0153] Furthermore, for each identified external dependency, its information is constructed into structured data (e.g., JSON objects) during AST traversal. This data is stored in a temporary data structure in real time and output after subsequent processing.

[0154] Furthermore, dependency information from all external dependencies can be integrated to generate a unified dependency mapping table for subsequent modules to call. Specifically, all recorded dependency information is summarized, duplicate and redundant data is checked, and data redundancy removal is performed. This forms a dependency mapping table where each entry includes:

[0155] Basic metadata: Dependency object name, type, call location, and key parameter information.

[0156] Mock configuration: generation rules (such as exception triggering conditions) and predefined data templates (such as return value structures).

[0157] Output the mapping table in a uniform format (such as JSON, XML, or key-value pair format) and save it to a database (such as Redis) for easy querying and dynamic updates by subsequent modules.

[0158] Furthermore, the dependency information includes the dependent object name, invocation location, dependency type, and key parameter information; the method also includes:

[0159] Step e1: Listen to the source code file of the target program.

[0160] Here, this embodiment of the application can automatically detect code modifications related to Mock objects by monitoring changes in the Git code repository. Specifically, when the code involves changes to Mock objects and their Mock rules, 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 scenario. First, the source code files of the target program are monitored.

[0161] Specifically, it monitors Git commit changes, uses Git Hooks (such as post-commit or pre-push) to automatically detect the most recently committed Java code changes, and obtains a list of affected ".java" files using "git diff". In this embodiment, a trigger script is added to the Git Hook to automatically detect the Java code changes in the most recent Git commit. The code differences between the current and previous commits are analyzed using gitdiff to extract the list of affected ".java" files. The command ":git diff --name-only HEAD~1 HEAD | grep ".java"" is executed to parse the output and obtain all changed Java source files. For example, "src / main / java / com / example / service / OrderService.java".

[0162] Step e2: If the source code file of the target program is changed, based on the changed source code file, determine whether the names of the dependent objects, the calling locations, the dependency types, and the key parameter information of each external dependency have changed.

[0163] Here, tools such as Eclipse JDT or Spoon are used to parse the affected Java files, extract the changed methods, and determine whether the names, call locations, dependency types, and key parameter information of each external dependency have changed. For example, when a modification to the "findOrderById" method in "OrderService" is detected, the dependency "orderRepository.findById" is analyzed.

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

[0165] Here, if changes are detected in the name, call location, dependency type, or key parameter information of an external dependency, the Mock object and Mock rules of the external dependency are determined based on the changed dependency information.

[0166] For example, in a code update, the method "orderRepository.findById(int id)" is changed to "findById(String id)", causing the parameter type to change 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.

[0167] To address this scenario, specifically, after listening to a Git commit, the signature change of the "orderRepository.findById" method is detected, and the new method signature "findById(String id)" is recorded. A static analysis tool (EclipseJDT) is used to determine the change in the method parameter type. Upon detecting the change from "int" to "String", the data type of "id" in the mock rule is automatically updated. Furthermore, to support a rollback mechanism for mock rules, version number management can be used, recording multiple historical versions to prevent erroneous updates from affecting tests. The mock rule before optimization can be represented as:

[0168] "orderRepository:

[0169] findById:

[0170] defaultReturn: { id: 1, name: "Laptop", quantity: 10}".

[0171] The optimized Mock rules can be expressed as:

[0172] "orderRepository:

[0173] findById:

[0174] versions:

[0175] - { version: "1.0", defaultReturn: { id: 1, name: "Laptop"}}

[0176] - { version: "1.1", defaultReturn: { id: 1, name: "Laptop", discount:10}}

[0177] activeVersion: "1.1" # Allows dynamic version switching.

[0178] For example, in a test scenario involving API changes, a developer modifies the return value of "restTemplate.getForObject("https: / / api.example.com / order / {id}")" by adding a "discountPrice" field. In this case, the mock rules need to be updated synchronously to match the new API response structure.

[0179] Specifically, for this scenario, after listening to a Git commit, the system checks if the return value structure of the Order object has changed. If a new "discountPrice" field is found, the Mock rules are updated. The returned value after the API change is parsed to extract the new field. The Mock rules are automatically updated to ensure that the returned JSON structure is consistent with the latest API. The original Mock rules can be represented as follows:

[0180] restTemplate:

[0181] getForObject:

[0182] defaultReturn: { status: "success", data: { id: 1, name: "Laptop"}}".

[0183] The optimized Mock rules can be expressed as:

[0184] restTemplate:

[0185] getForObject:

[0186] defaultReturn: { status: "success", data: { id: 1, name: "Laptop",discountPrice: 99.99}}".

[0187] Furthermore, the method also includes:

[0188] Step f1: Construct a dependency mapping table for the target program based on 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 object corresponding to each external dependency.

[0189] Here, automatically generated mock objects are integrated with external dependency information to establish a unified mapping relationship and provide a dynamic configuration interface. This allows for real-time adjustments to mock behavior during testing to meet evolving testing needs and ensure the consistency between returned data and business logic. The dependency information corresponds to basic metadata in the mapping table (including dependency object name, type, call location, and key parameter information), while the mock rules correspond to mock configurations in the mapping table (including generation rules and predefined data templates). The two are linked through a hierarchical data structure.

[0190] First, iterate through the dependency information of external dependencies obtained in S101, create a mapping entry for each external dependency, and save the mapping table using a data structure (such as JSON format).

[0191] The library defines a configuration structure in JSON or YAML format, allowing users to modify the return data of the Mock object, exception handling, and other settings.

[0192] Specifically, using the dependency information of all external dependencies obtained in S101, a mapping entry is created for each external dependency. This entry contains:

[0193] Basic metadata:

[0194] Dependency object name: for example, "orderRepository", "restTemplate", "kafkaTemplate";

[0195] Dependency types: Database dependency / HTTP API dependency / Message queue dependency;

[0196] Invocation location: Class name + method name (e.g., "OrderService.getOrderById");

[0197] Key parameter information: such as URL path, query conditions, and message subject.

[0198] Mock configuration:

[0199] Generation rule: Exception trigger threshold (e.g., "throw an exception when the parameter is null").

[0200] Predefined data template:

[0201] Database dependency: "Order(1, \"Laptop\", 10)".

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

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

[0204] Example of a JSON structure:

[0205] {

[0206] "orderRepository": {

[0207] "metadata": {

[0208] "type": "database dependency",

[0209] "location": "OrderService.findOrderById()",

[0210] "keyParams": {

[0211] "queryMethod": "findById",

[0212] "paramType": "String",

[0213] "requiredFields": ["id", "name"],

[0214] "constraints": { "minLength": 1, "maxLength": 36}

[0215] }

[0216] },

[0217] "mockConfig": {

[0218] "rules": {

[0219] "defaultReturn": { "id": 1, "name": "Laptop"},

[0220] "exceptions": { "nullParam": "throw IllegalArgumentException"}

[0221] }

[0222] }

[0223] }

[0224] }

[0225] ".

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

[0227] This application's embodiments design a configuration interface that allows 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 latency, etc. First, the configuration file structure is defined to ensure that each dependency's mapping entry contains all adjustable parameters. A configuration management service is developed that loads the configuration file at system startup and monitors file changes during runtime (or performs online configuration modifications through a 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 a RESTful API, allowing testers to submit configuration modification requests online for immediate effect. The configuration interface must support online dynamic modification, applying the new mock policy to the system immediately. The system periodically or in real-time monitors the configuration file status, automatically reloading and updating all relevant modules when a configuration change is detected. That is, in response to adjustments to the mock rules of any mock object in the dependency mapping table, the updated mock rules of the mock object are obtained.

[0228] Specifically, a file monitoring mechanism (such as using the Java WatchService API) is implemented in the configuration management service to automatically trigger a reload when a file changes. The latest configuration data is updated in the internal mapping table, and the Mock rules for the Mock object are notified to be reconfigured via a message queue or event notification mechanism. The configuration data is read to ensure that the latest configuration is used every time a Mock object is generated. For example, when test feedback indicates that the data returned by a certain HTTP API Mock object deviates significantly, testers can modify the configuration items in the YAML file online, such as adjusting the returned JSON data structure. Upon detecting the change, the configuration management service immediately updates the Mock rules for that HTTP API Mock object in the dependency mapping table, and all subsequent calls to that HTTP API Mock object use the new configuration to return data.

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

[0230] Based on the same application concept, this application also provides a Mock object adjustment device corresponding to the Mock object adjustment method provided in the above embodiments. Since the principle of the device in this application to solve the problem is similar to the Mock object adjustment method in the above embodiments of this application, the implementation of the device can refer to the implementation of the method, and the repeated parts will not be described again.

[0231] Please see Figure 2 , Figure 2 This is one of the functional block diagrams of a Mock object adjustment device provided in an embodiment of this application. Figure 2 As shown, the adjustment device 200 for the Mock object includes:

[0232] The data acquisition module 210 is used to extract dependency information of each external dependency of the target program from the target program to be tested.

[0233] The rule determination module 220 is used to determine, for any of the external dependencies, the Mock object of the external dependency and the Mock rules of the Mock object based on the dependency information of the external dependency.

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

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

[0236] Furthermore, when the rule adjustment module 240 dynamically adjusts the Mock rules of the Mock object based on the current test return results, historical test return results, and the Mock rule prediction model, the rule adjustment module 240 is specifically used for:

[0237] Based on the current test return results and historical test return results of the Mock object, the current input features and historical input features of the Mock object are determined; wherein, the historical input features include anomaly frequency matrix, time decay factor and rule stability index;

[0238] The Mock rule prediction model is trained based on the historical input features of the Mock object to obtain the trained Mock rule prediction model.

[0239] The current input features of the Mock object are input into the trained Mock rule prediction model to obtain the optimal prediction return value and the prediction anomaly return rate of the Mock object; the prediction anomaly return rate is generated by analyzing the anomaly frequency matrix.

[0240] 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.

[0241] 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 the trained Mock rule prediction model, the rule adjustment module 240 is specifically used for:

[0242] The decision tree module is trained based on the historical input features of the Mock object to obtain the trained decision tree module and generate the preliminary prediction result of the Mock object; the preliminary prediction result includes the preliminary prediction return value and the preliminary prediction anomaly return rate of the Mock object.

[0243] The random forest module is trained based on the preliminary prediction results of the mock object to obtain the trained random forest module and generate the optimized prediction results of the mock object; the optimized prediction results include the optimized prediction return value and the optimized prediction anomaly return rate of the mock object; the output node of the decision tree module is probabilistically coupled with the feature sampler of the random forest module.

[0244] The Bayesian optimization module is trained based on the optimized prediction results to obtain the trained Bayesian optimization module; the Bayesian optimization module includes a prior distribution correction unit, which is used to adjust the Gaussian process kernel function according to the out-of-bag error of the random forest module;

[0245] 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 dynamically adjusts the Mock rules 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 for:

[0246] If the predicted optimal return value is not among the return values ​​of the Mock rule, then the predicted optimal return value is added, and the usage weights of each return value are reallocated.

[0247] If the predicted anomaly return rate is greater than the first anomaly return rate threshold and less than or equal to the second anomaly return rate threshold, then the weight of the predicted optimal return value is reduced.

[0248] If the predicted anomaly return rate is greater than the second anomaly return rate threshold, and the Mock rule contains anomaly response configuration, then the Mock rule will be rolled back to the previous version.

[0249] Furthermore, the data acquisition module 210 is used to extract dependency information of each external dependency of the target program from the target program to be tested according to the following steps:

[0250] Convert the source code file of the target program into an abstract syntax tree;

[0251] Traverse all method call nodes, variable declaration nodes, and reference nodes in the abstract syntax tree, and filter out target nodes whose identifiers, method names, or method calls contain the keyword "external dependency" from each node;

[0252] Based on the target node, extract the dependency information of each external dependency of the target program.

[0253] Further, please refer to Figure 3 , Figure 3 This is a second functional block diagram of a Mock object adjustment device provided in an embodiment of this application. The dependency information includes the dependent object name, call location, dependency type, and key parameter information; such as... Figure 3 As shown, the adjustment device 200 for the Mock object also includes:

[0254] Modify the monitoring module 250 to monitor the source code files of the target program;

[0255] The change judgment module 260 is used to determine whether the names, call locations, dependency types, and key parameter information of each external dependency have changed if the source code file of the target program has been changed, based on the changed source code file.

[0256] The change determination module 270 is used to determine, if yes, the Mock object of the external dependency and the Mock rules of the Mock object based on the dependency information of the external dependency after the change, for any changed external dependency.

[0257] Furthermore, such as Figure 3 As shown, the adjustment device 200 for the Mock object also includes:

[0258] The dependency mapping module 280 is used to construct a dependency mapping table for the target program based on 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 object corresponding to each external dependency;

[0259] The manual adjustment module 290 is used to obtain the updated Mock rules of the Mock object in response to the adjustment operation of the Mock rules for any Mock object in the dependency mapping table.

[0260] This application provides a device for adjusting a Mock object, comprising: a data acquisition module for extracting dependency information of each external dependency of the target program from the target program to be tested; a rule determination module for determining, based on the dependency information of any external dependency, a Mock object and its Mock rules for that external dependency; a test execution module for performing call tests on any Mock object based on its Mock rules to obtain the current test return result; and a rule adjustment module for dynamically adjusting the Mock rules of the Mock object based on its current test return result, historical test return results, and a Mock rule prediction model. In this way, by combining the current and historical test return results of the Mock object and adjusting the Mock rules through a Mock rule prediction model, the efficiency of adjusting Mock objects in automated testing is improved.

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

[0262] The memory 420 stores machine-readable instructions executable by the processor 410. When the electronic device 400 is running, the processor 410 and the memory 420 communicate through the bus 430. When the machine-readable instructions are executed by the processor 410, the steps of the adjustment method of the Mock object provided in the above embodiment are executed. For specific implementation, please refer to the method embodiment, which will not be repeated here.

[0263] Based on the same concept, this application also provides a computer-readable storage medium storing a computer program. When the computer program is run by a processor, it executes the steps of the adjustment method for the Mock object provided in the above embodiments. For specific implementation details, please refer to the method embodiments, which will not be repeated here.

[0264] Those skilled in the art will clearly understand that, for the sake of convenience and brevity, the specific working process of the above-described apparatus and unit can be referred to the corresponding process in the foregoing method embodiments, and will not be repeated here.

[0265] In the embodiments provided in this application, it should be understood that the disclosed apparatus and methods can be implemented in other ways. The apparatus embodiments described above are merely illustrative. For example, the division of units is only a logical functional division, and in actual implementation, there may be other division methods. Furthermore, multiple units or components may be combined or integrated into another system, or some features may be ignored or not executed. Additionally, the displayed or discussed mutual couplings, direct couplings, or communication connections may be through some communication interfaces; indirect couplings or communication connections between devices or units may be electrical, mechanical, or other forms.

[0266] The units described as separate components may or may not be physically separate. 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 the units can be selected to achieve the purpose of this embodiment according to actual needs.

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

[0268] If the aforementioned functions are implemented as 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 this application, in essence, or the part that contributes to the prior art, or a portion of the technical solution, can be embodied in the form of a software product. This computer software product is stored in a storage medium and includes several instructions to cause a computer device (which may be a personal computer, server, or network device, etc.) to execute all or part of the steps of the methods described in the various embodiments of this application. The aforementioned storage medium includes various media capable of storing program code, such as USB flash drives, portable hard drives, read-only memory (ROM), random access memory (RAM), magnetic disks, or optical disks.

[0269] It should be noted that similar labels and letters in the following figures indicate similar items. 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 used only to distinguish descriptions and should not be construed as indicating or implying relative importance.

[0270] Finally, it should be noted that the above-described embodiments are merely specific implementations of this application, used to illustrate the technical solutions of this application, and not to limit them. The protection scope of this application is not limited thereto. Although this application has been described in detail with reference to the foregoing embodiments, those skilled in the art should understand that any person skilled in the art can still modify or easily conceive of changes to the technical solutions described in the foregoing embodiments, or make equivalent substitutions for some of the technical features, within the scope of the technology disclosed in this application; and these modifications, changes, or substitutions do not cause the essence of the corresponding technical solutions to deviate from the spirit and scope of the technical solutions of the embodiments of this application. All should be covered within the protection scope of this application. Therefore, the protection scope of this application should be determined by the protection scope of the claims.

Claims

1. A method for adjusting a Mock object, characterized in that, The method includes: Extract dependency information for each external dependency of the target program to be tested; For any of the aforementioned external dependencies, based on the dependency information of the external dependency, determine the Mock object of the external dependency and the Mock rules of the Mock object; For any of the aforementioned Mock objects, based on the Mock rules of the Mock object, a call test is performed on the Mock object to obtain the current test return result of the Mock object; Based on the current test return results, historical test return results, and the Mock rule prediction model of the Mock object, the Mock rules of the Mock object are dynamically adjusted, including: Based on the current test return results and historical test return results of the Mock object, the current input features and historical input features of the Mock object are determined; wherein, the historical input features include anomaly frequency matrix, time decay factor and rule stability index; The Mock rule prediction model is trained based on the historical input features of the Mock object to obtain the trained Mock rule prediction model, including: The decision tree module is trained based on the historical input features of the Mock object to obtain the trained decision tree module and generate the preliminary prediction result of the Mock object; the Mock rule prediction model includes a decision tree module, a random forest module and a Bayesian optimization module; the preliminary prediction result includes the preliminary prediction return value and the preliminary prediction anomaly return rate of the Mock object. The random forest module is trained based on the preliminary prediction results of the mock object to obtain the trained random forest module and generate the optimized prediction results of the mock object; the optimized prediction results include the optimized prediction return value and the optimized prediction anomaly return rate of the mock object; the output node of the decision tree module is probabilistically coupled with the feature sampler of the random forest module. The Bayesian optimization module is trained based on the optimized prediction results to obtain the trained Bayesian optimization module; the Bayesian optimization module includes a prior distribution correction unit, which is used to adjust 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; The current input features of the Mock object are input into the trained Mock rule prediction model to obtain the optimal prediction return value and the prediction anomaly return rate of the Mock object; the prediction anomaly return rate is generated by analyzing the anomaly frequency matrix. 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, including: If the predicted optimal return value is not among the return values ​​of the Mock rule, then the predicted optimal return value is added, and the usage weights of each return value are reallocated. If the predicted anomaly return rate is greater than the first anomaly return rate threshold and less than or equal to the second anomaly return rate threshold, then the weight of the predicted optimal return value is reduced. If the predicted anomaly return rate is greater than the second anomaly return rate threshold, and the Mock rule contains anomaly response configuration, then the Mock rule will be rolled back to the previous version.

2. The method for adjusting a Mock object according to claim 1, characterized in that, Extract dependency information for each external dependency of the target program to be tested from the following steps: Convert the source code file of the target program into an abstract syntax tree; Traverse all method call nodes, variable declaration nodes, and reference nodes in the abstract syntax tree, and filter out target nodes whose identifiers, method names, or method calls contain the keyword "external dependency" from each node; Based on the target node, extract the dependency information of each external dependency of the target program.

3. The method for adjusting a Mock object according to claim 2, characterized in that, The dependency information includes the name of the dependent object, the call location, the dependency type, and key parameter information; the method also includes: Monitor the source code files of the target program; If the source code file of the target program is changed, based on the changed source code file, determine whether the names of the dependent objects, the calling locations, the dependency types, and the 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 the Mock object of the external dependency and the Mock rules of the Mock object.

4. The method for adjusting a Mock object according to claim 3, characterized in that, The method further includes: Based on the dependency information of each external dependency of the target program, a dependency mapping table of the target program is constructed; the dependency mapping table includes the dependency information of each external dependency and the Mock rules of the Mock object corresponding to each external dependency; In response to the adjustment operation of the Mock rule for any Mock object in the dependency mapping table, the updated Mock rule for the Mock object is obtained.

5. An adjustment device for a mock object, characterized in that, The adjustment device for the Mock object includes: The data acquisition module is used to extract dependency information of each external dependency of the target program from the target program to be tested; The rule determination module is used to determine, for any of the external dependencies, the Mock object of the external dependency and the Mock rules of the Mock object based on the dependency information of the external dependency; The test execution module is used to perform call tests on any of the Mock objects based on the Mock rules of the Mock objects, and obtain the current test return result of the Mock objects; The rule adjustment module is used to dynamically adjust the Mock rules of the Mock object based on the current test return results, historical test return results, and the Mock rule prediction model, including: Based on the current test return results and historical test return results of the Mock object, the current input features and historical input features of the Mock object are determined; wherein, the historical input features include anomaly frequency matrix, time decay factor and rule stability index; The Mock rule prediction model is trained based on the historical input features of the Mock object to obtain the trained Mock rule prediction model, including: The decision tree module is trained based on the historical input features of the Mock object to obtain the trained decision tree module and generate the preliminary prediction result of the Mock object; the Mock rule prediction model includes a decision tree module, a random forest module and a Bayesian optimization module; the preliminary prediction result includes the preliminary prediction return value and the preliminary prediction anomaly return rate of the Mock object. The random forest module is trained based on the preliminary prediction results of the mock object to obtain the trained random forest module and generate the optimized prediction results of the mock object; the optimized prediction results include the optimized prediction return value and the optimized prediction anomaly return rate of the mock object; the output node of the decision tree module is probabilistically coupled with the feature sampler of the random forest module. The Bayesian optimization module is trained based on the optimized prediction results to obtain the trained Bayesian optimization module; the Bayesian optimization module includes a prior distribution correction unit, which is used to adjust 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; The current input features of the Mock object are input into the trained Mock rule prediction model to obtain the optimal prediction return value and the prediction anomaly return rate of the Mock object; the prediction anomaly return rate is generated by analyzing the anomaly frequency matrix. 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, including: If the predicted optimal return value is not among the return values ​​of the Mock rule, then the predicted optimal return value is added, and the usage weights of each return value are reallocated. If the predicted anomaly return rate is greater than the first anomaly return rate threshold and less than or equal to the second anomaly return rate threshold, then the weight of the predicted optimal return value is reduced. If the predicted anomaly return rate is greater than the second anomaly return rate threshold, and the Mock rule contains anomaly response configuration, then the Mock rule will be rolled back to the previous version.

6. An electronic device, characterized in that, include: The device includes a processor, a memory, and a bus. The memory stores machine-readable instructions executable by the processor. When the electronic device is running, the processor communicates with the memory via the bus. The machine-readable instructions are executed by the processor to perform the steps of the adjustment method for the Mock object as described in any one of claims 1 to 4.

7. A computer-readable storage medium, characterized in that, The computer-readable storage medium stores a computer program that, when executed by a processor, performs the steps of the adjustment method for the Mock object as described in any one of claims 1 to 4.

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