软件测试中数据验证的3大难题,这个工具搞定!
liebian365 2025-01-12 16:18 13 浏览 0 评论
应用场景:
随着系统开发日益模块化和分布式部署服务器的普及,测试过程中常常需要验证与后端服务之间频繁数据交换的完整性。然而,实际操作中可能面临多重挑战:
·后端开发未完成: 后端服务可能尚在开发中,导致无法展开全面的测试。
· 权限限制: 测试人员可能因为权限问题无法访问后端数据,从而限制了对数据交换过程的验证。
· 第三方开发: 后端服务可能由第三方团队开发,增加了对其进行有效集成测试的难度。
这些因素使得客户端的测试范围受到限制,集成测试变得愈加困难。尤其是在验证客户端数据发送的完整性和正确性时,团队面临着巨大的挑战。在这种复杂的系统架构中,确保客户端发送的数据能够准确地到达服务器至关重要。
今天的示例中通过搭建一个WireMock 服务器模拟接受客户端发送的数据,然后在一定时间内去验证服务器接收到数据数量与次数,从而达到验证客户端是否发送了预期的数据。
注意,这个用例与现实业务中的连接挑战有3个方面: 1) 依照场景测试要求自动化触发API 请求的功能点,2) 把现实业务中的请求地址改成WireMock 中配置的路径,3) 依照业务需求验证记录监控中数据与期待值的一致性。 为了解决这些挑战,有的需要和开发沟通,有的要和业务需求方进行讨论。唯有这样,才能更准确的进行自动化测试。
温馨提示:如果您要按着示例一起做,请务必配置如下工具以及学习相关的知识。 用例主要是搭建启动一个WireMock 服务器,利用Rest-Assured完成API 的数据发送 (实际项目中,要通过客户端项目的功能触发API 的数据发送) ,然后通过验证服务器接收到的数据来确认API 的数据发送是否成功。
· IDE: IntelliJ IDEA
· 语言: Java
· API 请求: Rest-Assured
· API服务器 :WireMock
· 测试框架:TestNg
· 项目类型: Maven
知识重点:
· WireMock 的POST 构建 与启动 : 了解如何创建和配置 WireMock 服务器,设置 POST 请求的 stub,以便模拟真实的 API 行为。
· Rest Assured 模拟API 请求:使用 Rest Assured 库发送模拟的 API POST 请求
· WireMock API 获取POST 数据: 掌握如何通过 WireMock API 获取接收到的 POST 数据,以进行后续的验证和分析。
一、 分解用例
假设有一个待测试的系统功能,即数据发送功能,测试的重点是确保该功能发送的数据完整性。最好的方法是在触发数据发送后,前往服务器端将接收到的数据与发送的数据进行对比,以验证每个字段的正确性并确保没有数据丢失。同时,对于其他测试要求,比如连续触发该功能的数据发送,以确保该功能没有延迟或丢失任何数据。目前遇到的问题是,无法直接访问服务器端验证接收到的数据。
对于这个测试需求,本示例使用 WireMock 工具搭建了一个模拟服务器,来替代真实的后端服务。通过这种方式,可以在本地测试数据发送功能:
· 搭建并启动Mock 服务器 : 创建一个 WireMock 服务器来模拟真实的后端数据接收接口。
· 发送数据: 触发本地系统的数据发送功能(示例中使用 RestAssured 模拟数据发送,为了更好地验证数据发送功能,这里数据的发送是在一个新线程中完成的。这样就能动态地监控服务器接收数据的状况,换句话说就能动态地测试当前系统的数据发送功能。)
· 监控记录请求: Mock 服务器会记录所有接收到的请求,包括发送的数据。
· 比对数据: 在监控过程中,可以WireMock 服务器里获取记录的数据从而来确定数据发送功能未被篡改且没有丢失数据。同时在验证大量数据发送过程中,可以通过设置超时,来确认数据发送功能没有延迟或数据丢失。
理解了基本的测试场景,以及相对应的测试步骤流程。一起来实现它吧,让测试变得更加高效起来吧。
二、 Maven 配置
本次示例搭建 WireMork 服务器需要用到的3个插件。
<dependency>
<groupId>com.github.tomakehurst</groupId>
<artifactId>wiremock-jre8</artifactId>
<version>3.0.1</version>
<type>pom</type>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-servlet</artifactId>
<version>11.0.22</version>
</dependency>
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-server</artifactId>
<version>11.0.22</version>
</dependency>
三 、代码解析
以下代码给出了完整的测试用例执行流程,且对每一个方法进行了逐一解释。
1.构建WireMock 服务器: 方法startWireMockServer() 先创建了 WireMockServer 实例, 并按接收到的指定端口进行监听。接着,启动服务器并配置 WireMock,使其能够处理特定的 HTTP 请求。最后,它设置一个 stub,以便在接收到 POST 请求到 /api/data/receive 的时候,返回一个 200 状态的响应,并包含 Content-Type 为 application/json 的头信息。
2.新建一个新线程Thread dataSendRequest 执行sendPost()方法。sendPost 利用RestAssured 会每隔100 毫秒发送一次数据到MockServer,重复发送100 次且从第51次开始,发送内容testPostInvalid。
3.dataValidation() 方法先通过调用receivedDataMonitor()方法获取MockServer 收到的请求数据接着,再对请求的数据进行内容与大小的验证。
4.receivedDataMonitor()方法每500 毫秒循环一次地按接收到的时间分别把请求的次数保存以做延迟性验证(示例中只给了10秒,只是为了讲解用例而已)。
5.最后是合并线程和关闭MockServer 服务器。
@Test(description = "To Verify Data Sending Integrity ")
public void testDataIntegrity() {
// Setup Mock Server
wireMockServer = startWireMockServer(9090);
long threshold = 10;
int eventSentCount = 100;
//Step To Send Data In a New Thread
baseURI = "http://localhost:9090/api/data/receive";
Thread dataSendRequest = new Thread(() -> {
try {
sendPost(eventSentCount, 100);
} catch (Exception e) {
System.out.println("Error: Sending Data");
}
});
dataSendRequest.start();
// Verify Data Sending Integrity
dataValidation(eventSentCount, threshold);
// Send Data Thread Join
try {
dataSendRequest.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
// Stop WireMock Server
stopWireMockServer(wireMockServer);
}
——————————
WireMockServer startWireMockServer(int port) {
WireMockServer wireMockServer = new WireMockServer(port);
wireMockServer.start();
configureFor("localhost", port);
stubFor(post(urlEqualTo("/api/data/receive"))
.willReturn(aResponse()
.withStatus(200).
withHeader("Content-Type", "application/json")));
return wireMockServer;
}
void sendPost(int repeatTime, int interval) {
String requestBody = null;
long startTime = System.currentTimeMillis();
for (int i = 0; i < repeatTime; i++) {
if (i < repeatTime / 2) {
requestBody = "{\"testPost\":\"testing data\"}";
} else {
requestBody = "{\"testPostInvalid\":\"testing data\"}";
}
given().contentType("application/json").body(requestBody).post();
// Wait for interval
waitForNext(interval);
}
long endTime = System.currentTimeMillis();
long totalTime = endTime - startTime;
System.out.println("Total Time Spent: " + totalTime + " Milliseconds");
}
}
——————————
void dataValidation(int expectedReceivedDataCount, long threshold) {
ObjectMapper objectMapper = new ObjectMapper();
List<ServeEvent> serverEvents = receivedDataMonitor(expectedReceivedDataCount, threshold);
int totalContentReceived = 0;
int invalidContentSize = 0;
int invalidContent = 0;
// Validate Post Count
if (!(serverEvents.size() == expectedReceivedDataCount)) {
System.out.println("Error Received Post Count Does Not As Expected");
} else {
// Validate Post Content
for (ServeEvent event : serverEvents) {
totalContentReceived++;
String postBody = event.getRequest().getBodyAsString();
try {
Map<String, Object> postData = objectMapper.readValue(postBody, new TypeReference<Map<String, Object>>() {
});
// Validate Size Of Each Post
if (postBody.length() > 10240) { // 10 KB limit
invalidContentSize++;
//System.out.println("Error: Post Content Exceeds 10 KB: " + postBody);
}
// Validate Field Existence In Each Post
if (!postData.containsKey("testPost")) {
invalidContent++;
//System.out.println("Error: Post Content Does Not Include 'testPost': " + postBody);
}
} catch (IOException e) {
System.out.println("Error: Failed to Parse Post Body: " + postBody);
}
}
}
System.out.println("Info Total Received Post Count : " + totalContentReceived);
System.out.println("Info Total Received Post Count With Invalid Content Size: " + invalidContentSize);
System.out.println("Info Total Received Post Count With Invalid Content : " + invalidContent);
Assert.assertEquals(expectedReceivedDataCount, serverEvents.size(), "Error Received Post Count Does Not As Expected");
Assert.assertEquals(expectedReceivedDataCount, totalContentReceived, "Error Total Received Post Count As Expected");
Assert.assertEquals(invalidContentSize, 0, "Error Total Received Post Count With Invalid Content Size Not As Expected");
Assert.assertEquals(invalidContent, 50, "Error Total Received Post Count With Invalid Content s Not As Expected");
}
——————————
private List<ServeEvent> receivedDataMonitor(int expectedReceivedDataCount, long threshold) {
long startTime = System.currentTimeMillis();
long timeBox = TimeUnit.SECONDS.toMillis(40);
long firstInterval = TimeUnit.SECONDS.toMillis(threshold);
long loopStartTime = System.currentTimeMillis();
long elapsedTime = 0;
List<ServeEvent> serverEvents = null;
boolean bValidation = false;
int totalReceivedPCCount =0;
while (System.currentTimeMillis() - startTime < timeBox) {
serverEvents = wireMockServer.getAllServeEvents();
long currentTime = System.currentTimeMillis();
// Determine Posts Count Were Received in As Per Threshold
if (currentTime - startTime < firstInterval) {
receivedPCWithInThreshold = serverEvents.size();
} else {
receivedPCOutOfThreshold = serverEvents.size() - receivedPCWithInThreshold;
}
//System.out.println("Info Received Post Count (First " + threshold + " seconds): " + receivedPCWithInThreshold);
//System.out.println("Info Received Post Count (After " + threshold + " seconds): " + receivedPCOutOfThreshold);
totalReceivedPCCount = receivedPCWithInThreshold + receivedPCOutOfThreshold;
if (totalReceivedPCCount == expectedReceivedDataCount && !bValidation) {
long currentLoopTime = System.currentTimeMillis();
elapsedTime = currentLoopTime - loopStartTime;
System.out.println("Info Received Post Count " + receivedPCWithInThreshold + " Within " + threshold + "(Mills)");
System.out.println("Info Received Post Count " + receivedPCOutOfThreshold + " Out of " + threshold + "(Mills)");
System.out.println("Info Received Post Count " + totalReceivedPCCount + " Spend Total Period (Mills): " + elapsedTime);
bValidation = true;
}
if (totalReceivedPCCount > expectedReceivedDataCount) {
System.out.println("Error: Received Post Count Exceeds Expected " + expectedReceivedDataCount);
}
waitForNext(500);
}
boolean verifiedDataReceived = totalReceivedPCCount == expectedReceivedDataCount;
Assert.assertTrue(verifiedDataReceived && elapsedTime<=15000,"Error: Received Post Count Exceeds Expected" );
return serverEvents;
}
——————————
void stopWireMockServer(WireMockServer wireMockServer) {
wireMockServer.stop();
}
四、结语
如上所述,这种方法能够很快地确保验证客户端请求的次数与内容的准确性在限制的时间内,并根据业务需求进一步验证请求具体内容和大小。从而提升系统的可靠性和数据一致性。用在自动化测试框架里,既能保证快速有效的测试,同时也能保证测试结果的稳定性,从而降低代码的维护。此外,它还能够准确定位潜在问题,使开发团队更高效地进行调试和优化,从而进一步提升系统的整体质量。
文末了,我邀请你进入我们的软件测试学习交流群,大家可以一起探讨交流软件测试,共同学习软件测试技术、面试等软件测试方方面面,了解测试行业的最新趋势,助你快速进阶Python自动化测试/测试开发,稳住当前职位同时走向高薪之路。
最后:
1)关注+私信回复:“测试”,可以免费领取一份10G软件测试工程师面试宝典文档资料。以及相对应的视频学习教程免费分享!
2)关注+私信回复:"入群" 就可以邀请你进入软件测试群学习交流~~
相关推荐
- 4万多吨豪华游轮遇险 竟是因为这个原因……
-
(观察者网讯)4.7万吨豪华游轮搁浅,竟是因为油量太低?据观察者网此前报道,挪威游轮“维京天空”号上周六(23日)在挪威近海发生引擎故障搁浅。船上载有1300多人,其中28人受伤住院。经过数天的调...
- “菜鸟黑客”必用兵器之“渗透测试篇二”
-
"菜鸟黑客"必用兵器之"渗透测试篇二"上篇文章主要针对伙伴们对"渗透测试"应该如何学习?"渗透测试"的基本流程?本篇文章继续上次的分享,接着介绍一下黑客们常用的渗透测试工具有哪些?以及用实验环境让大家...
- 科幻春晚丨《震动羽翼说“Hello”》两万年星间飞行,探测器对地球的最终告白
-
作者|藤井太洋译者|祝力新【编者按】2021年科幻春晚的最后一篇小说,来自大家喜爱的日本科幻作家藤井太洋。小说将视角放在一颗太空探测器上,延续了他一贯的浪漫风格。...
- 麦子陪你做作业(二):KEGG通路数据库的正确打开姿势
-
作者:麦子KEGG是通路数据库中最庞大的,涵盖基因组网络信息,主要注释基因的功能和调控关系。当我们选到了合适的候选分子,单变量研究也已做完,接着研究机制的时便可使用到它。你需要了解你的分子目前已有哪些...
- 知存科技王绍迪:突破存储墙瓶颈,详解存算一体架构优势
-
智东西(公众号:zhidxcom)编辑|韦世玮智东西6月5日消息,近日,在落幕不久的GTIC2021嵌入式AI创新峰会上,知存科技CEO王绍迪博士以《存算一体AI芯片:AIoT设备的算力新选择》...
- 每日新闻播报(September 14)_每日新闻播报英文
-
AnOscarstatuestandscoveredwithplasticduringpreparationsleadinguptothe87thAcademyAward...
- 香港新巴城巴开放实时到站数据 供科技界研发使用
-
中新网3月22日电据香港《明报》报道,香港特区政府致力推动智慧城市,鼓励公私营机构开放数据,以便科技界研发使用。香港运输署21日与新巴及城巴(两巴)公司签署谅解备忘录,两巴将于2019年第3季度,开...
- 5款不容错过的APP: Red Bull Alert,Flipagram,WifiMapper
-
本周有不少非常出色的app推出,鸵鸟电台做了一个小合集。亮相本周榜单的有WifiMapper's安卓版的app,其中包含了RedBull的一款新型闹钟,还有一款可爱的怪物主题益智游戏。一起来看看我...
- Qt动画效果展示_qt显示图片
-
今天在这篇博文中,主要实践Qt动画,做一个实例来讲解Qt动画使用,其界面如下图所示(由于没有录制为gif动画图片,所以请各位下载查看效果):该程序使用应用程序单窗口,主窗口继承于QMainWindow...
- 如何从0到1设计实现一门自己的脚本语言
-
作者:dong...
- 三年级语文上册 仿写句子 需要的直接下载打印吧
-
描写秋天的好句好段1.秋天来了,山野变成了美丽的图画。苹果露出红红的脸庞,梨树挂起金黄的灯笼,高粱举起了燃烧的火把。大雁在天空一会儿写“人”字,一会儿写“一”字。2.花园里,菊花争奇斗艳,红的似火,粉...
- C++|那些一看就很简洁、优雅、经典的小代码段
-
目录0等概率随机洗牌:1大小写转换2字符串复制...
- 二年级上册语文必考句子仿写,家长打印,孩子照着练
-
二年级上册语文必考句子仿写,家长打印,孩子照着练。具体如下:...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- wireshark怎么抓包 (75)
- qt sleep (64)
- cs1.6指令代码大全 (55)
- factory-method (60)
- sqlite3_bind_blob (52)
- hibernate update (63)
- c++ base64 (70)
- nc 命令 (52)
- wm_close (51)
- epollin (51)
- sqlca.sqlcode (57)
- lua ipairs (60)
- tv_usec (64)
- 命令行进入文件夹 (53)
- postgresql array (57)
- statfs函数 (57)
- .project文件 (54)
- lua require (56)
- for_each (67)
- c#工厂模式 (57)
- wxsqlite3 (66)
- dmesg -c (58)
- fopen参数 (53)
- tar -zxvf -c (55)
- 速递查询 (52)