当前位置:网站首页>Interface automation framework scaffolding - Implementation of parametric tools
Interface automation framework scaffolding - Implementation of parametric tools
2022-06-28 10:11:00 【Software quality assurance】
Continue to adhere to the original output , Click on the blue word to follow me

author : Software quality assurance
You know :https://www.zhihu.com/people/iloverain102
Today, I share a scaffolding tool used in the development of interface automation framework .
On topic speech
as everyone knows , The most important use case of interface automation is the test data , Test cases essentially depend on the combination of various data .
Friends who have done interface automation can think about , We are using postman or JMeter When writing use case scripts , It takes a lot of time to pass parameters between interfaces .
The parameter transfer between interfaces is realized through existing tools , It only needs to be in the downstream interface “ Variable ” Set up { {}} perhaps ${} that will do , And how to replace it seems that we haven't considered .
We have to face this problem when designing our own framework .
For microservice Architecture ( This article only discusses Java Stack ) Often the implementation of services is not based on http agreement , The interface is called through SPI(Service Provider Interface) Interface implementation , It can be simply understood as a standard service , It's a Service, Instead of HTTP Interface , Its request message is a Java object .
Everybody knows http The request parameter format of the protocol interface is mostly json Format , But this article introduces service The parameter format of the service is object .
therefore , For use case parameters ,service The implementation of service automation needs to solve two problems :
1. How to save messages , In what format ?
2. How parameterization is implemented ?
For testing ,json Format data is easy to assemble , because JSON The structure is more acceptable , And there's a lot of JSON Tools can be used , We just need to fill in the key value pairs according to the structure , And you can use JSON Format file saves test data .
But class objects are different , Classes are just definitions , Object is an instance of a class , Need to be in operation is new One comes out and assigns a value to it , So we can't do it in a specific format or File save class object .( Of course, you can also put the test data in the test code new An object comes out and assigns values , But it's too big )
As we all know JSON And objects are interchangeable , Everyone must have written code for mutual transformation , Alibaba also has an open source tool fastJSON.
OK, That solves the first problem , We can convert the class object to json, With json The file format saves the local as the message template.
And how to solve the other problem : How to parameterize and set JSON File to a specific object ?
In fact, it is relatively simple to solve this problem , We need to Parameterized variables Define as an object as Input, The request parameters of the interface — Parameterized variables are actually Data that the business doesn't want to do , It can be used as a message template .
So the parameterization process is actually to The contents of the parameterized object Replace the Message template in , Then replace the JSON To Object that will do . The figure below is easy to understand ..

Here is the code to implement this tool .
Code practice
The implementation of this tool , Need to rely on Apache Of velocity package .Apache Velocity It's based on Java Template engine for , It provides a template language to reference the Java Code defined objects .Velocity yes Apache An open source software project under the foundation , To ensure that Web The isolation of applications between the presentation layer and the business logic layer .
Here are some uses Velocity Common application scenarios :
Web Applications : Web designers create HTML page , And reserve placeholders for dynamic information . Page re by VelocityViewServlet Or any support Velocity Frame handling .
Source code generation :Velocity Can be generated based on the template Java、SQL or PostScript Source code . This is how a large number of open source and commercial software packages are developed Velocity.
E-mail is automatically generated : Many applications register for accounts 、 For password reminder or automatic report sending, e-mail should be generated automatically . utilize Velocity, Email templates can be stored in a text file , Instead of embedding directly into the email generator Java In the code .
XML conversion :Velocity Provide a Ant Mission ——Anakia.Anakia Read XML file , utilize Velocity Convert the template to the required document format . A common application is to convert a document of a certain format into a styled HTML file .
Okay , Just stop here , Now let's start the code quietly ...
Project structure

introduce velocity package
<dependency><groupId>org.apache.velocity</groupId><artifactId>velocity</artifactId><version>1.7</version></dependency><dependency><groupId>org.apache.velocity</groupId><artifactId>velocity-tools</artifactId><version>2.0</version></dependency>
The main logic
import org.apache.velocity.VelocityContext;/*** @author Software quality assurance* @version Json2Class.java, v 0.1 2022 year 06 month 24 Japan 19:48*/public class Json2Class {public static String evaluateString(String path, Object input) throws FileNotFoundException {InputStream is = new FileInputStream(path);Map<String, Object> context = new HashMap<>();Map<String, Object> paramMap = BeanMap.create(input);for (String key : paramMap.keySet()) {Object value = paramMap.get(key);if (value != null) {context.put(key, value);}}StringWriter writer = new StringWriter();String result;try {VelocityContext velocityContext = new VelocityContext(context);Velocity.evaluate(velocityContext, writer, "", is);result = writer.toString();} catch (Exception var8) {throw new TestException("velocity evaluate error[template=" + is + "]", var8);} finally {IOUtils.closeQuietly(writer);}return result;}public static <T> T reloadRequest(String path, Object input, Class<T> clazz) {try {String loadFile = evaluateString(path, input);T request = JSON.parseObject(loadFile, clazz);return request;} catch (FileNotFoundException e) {throw new RuntimeException("load request body failed",e);}}}
Test code
// Parameterized variable objects@Datapublic class Input {private String paymentId;private String token;private Order order;}public class Order {private String amount;private String currency;}// Target audience@Datapublic class Request {private String payId;private String paymentId;private String payType;private String token;private Order order;}// JSON Template{"payId": "238938392","token": "${token}","paymentId": "${paymentId}","payType": "CARD","order": {"amount": "${order.amount}","currency": "${order.currency}"}}// The client invokes the use casepublic class client {public static void main(String[] args) throws FileNotFoundException {// Prepare parameterized dataInput input = new Input();Order order = new Order();order.setAmount("1000");order.setCurrency("CNY");input.setPaymentId("test0001");input.setToken("card_token_9999292929");input.setOrder(order);Request request =Json2Class.loadRequestBody("request.json", input, Request.class);System.out.println(request);}}
Output results
Request(payId=238938392, paymentId=test0001, payType=CARD, token=card_token_9999292929, order=Order(amount=1000, currency=CNY))Be accomplished !!!
This case is relatively simple ,json There is no loop nesting multiple levels , No matter how many floors , It's essentially the same thing , You can try it yourself .
Like it , Just click on it. Zanhe is looking at Let's go , It's not easy to create , Ask for forwarding and attention
- END -
Scan the code below to pay attention to Software quality assurance , Learn and grow with quality gentleman 、 Common progress , Being a professional is the most expensive Tester!
The background to reply 【 Test open 】 Get test development xmind Brain map
The background to reply 【 Add group 】 Get to join the testing community !
边栏推荐
猜你喜欢

我大抵是卷上瘾了,横竖睡不着!竟让一个Bug,搞我两次!

Dotnet uses crossgen2 to readytorun DLL to improve startup performance

PMP Exam key summary VI - chart arrangement

适配器模式(Adapter)

增强 Jupyter Notebook 的功能,这里有四个妙招

SQL中的DQL、DML、DDL和DCL是怎么区分和定义的

再见!IE浏览器,这条路由Edge替IE继续走下去

错过金三银四,找工作4个月,面试15家,终于拿到3个offer,定级P7+

Function sub file writing

TCP实战案例之即时通信、BS架构模拟
随机推荐
flink cep 跳过策略 AfterMatchSkipStrategy.skipPastLastEvent() 匹配过的不再匹配 碧坑指南
An error is reported when uninstalling Oracle
解决表单action属性传参时值为null的问题
满电出发加速品牌焕新,长安电动电气化产品吹响“集结号”
云服务器MYSQL查询速度慢
Dbeaver installation and use tutorial (super detailed installation and use tutorial)
栈的弹出压入序列<难度系数>
Must the MySQL table have a primary key for incremental snapshots?
接口自动化框架脚手架-利用反射机制实现接口统一发起端
在OpenCloudOS使用snap安装.NET 6
R语言plotly可视化:plotly可视化互相重叠的直方图(histogram)、在直方图的底部边缘使用geom_rug函数添加边缘轴须图Marginal rug plots
QT signal and slot communication mechanism (when multiple windows communicate back and forth [parent and child windows])
Unity AssetBundle资源打包与资源加载
Solve the problem that the value of the action attribute of the form is null when transferring parameters
Stutter participle_ Principle of word breaker
学习机器学习的最佳路径是什么
Global exception handlers and unified return results
bye! IE browser, this route edge continues to go on for IE
TCP实战案例之即时通信、BS架构模拟
第三章 栈和队列