Design and Implementation of a Web Interface Mock Service at Huajiao
This article explains the concept of Mock objects for testing, outlines why interface mocking is essential in web development, and details Huajiao's comprehensive Mock solution—including a SpringBoot‑based backend, MySQL data storage, Nginx redirection, and Lua scripts for dynamic request routing—providing step‑by‑step usage instructions and code examples.
Mock objects simulate difficult‑to‑create or unavailable dependencies during testing; they are especially useful for web API testing. The article begins by defining Mock, its role in unit and integration testing, and the benefits it brings to frontend development, integration testing, complex scenario simulation, and error‑case verification.
Huajiao's Mock solution addresses several drawbacks of traditional Mock services, such as host binding changes, lack of multi‑user support, inability to customize per‑user responses, and cumbersome file‑based data management. The design goals are to simplify usage for frontend developers, support concurrent users with distinct data, and handle encrypted responses.
Mock Backend
The backend serves as a configuration center built with SpringBoot, MyBatis, and Vue. It provides APIs for displaying, adding, editing, and deleting Mock data, storing records in a MySQL table named mock with fields like uri, request, response, platform, encrypt, model, author, etc. Example controller method:
public RestResult findByUri(@RequestBody JSONObject request) throws Exception {
int offset = request.getIntValue("offset");
String uri = request.getString("uri");
uri = "%" + uri + "%";
List<MockData> data = mapper.getMockDataByUri(uri, offset);
for (MockData one : data) {
one.decryptData();
}
int total = mapper.getMockDataByUriTotal(uri);
return success(formatPageData(data, total, offset));
}Mock Service
The service processes incoming requests, matches them against stored Mock configurations, and returns the appropriate mocked response. It extends the open‑source Moco framework, adding database‑backed storage via MyBatis. Configuration priority rules ensure that user‑specific Mock data is matched before generic data.
Key MyBatis configuration snippet:
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://10.14.*.*:port/db_name?useUnicode=true&characterEncoding=utf-8"/>
<property name="username" value="username"/>
<property name="password" value="password"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper class="com.github.dreamhead.moco.MockMapper"/>
</mappers>
</configuration>Business Server Redirection
Requests from mobile or frontend applications first hit an Nginx layer where Lua scripts determine whether to forward the request to the Mock service. Two Lua endpoints are provided: /lua/pour to set Mock routing information into Nginx cache, and /lua/get to retrieve the current configuration. Example curl commands illustrate how to configure per‑user or per‑device routing.
Lua redirection logic (simplified):
local proxy_res = cache:get(project .. "_proxy")
if proxy_res and (ngx.req.get_headers()["x-proxy-host"] == nil or ngx.req.get_headers()["x-proxy-host"] == "") then
local status, proxy_cnf = pcall(function(proxy_res)
local cjson = require "cjson"
return cjson.decode(proxy_res)
end, proxy_res)
if status and type(proxy_cnf) == "table" then
if proxy_cnf[ngx.var.arg_userid] then
ngx.req.set_header("x-proxy-host", proxy_cnf[ngx.var.arg_userid])
ngx.exec("@proxy")
elseif proxy_cnf[ngx.var.arg_deviceid] then
ngx.req.set_header("x-proxy-host", proxy_cnf[ngx.var.arg_deviceid])
ngx.exec("@proxy")
end
end
endUsage Steps
Two usage patterns are described: (1) adding Mock data via the backend UI, configuring routing, and then making normal API calls from the client to receive the mocked response; (2) directly binding the target domain in hosts or Wi‑Fi DNS to the Mock server and accessing it through the network.
The article concludes with reflections on challenges such as multi‑user data isolation, HTTPS certificate handling, and future possibilities for automated testing integration.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
360 Tech Engineering
Official tech channel of 360, building the most professional technology aggregation platform for the brand.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
