当前位置:网站首页>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 !
边栏推荐
- Naming rules and specifications for identifiers
- 如何查看谷歌浏览器保存的网页密码
- 如图 用sql行转列 图一原表,图二希望转换后
- 增量快照 必须要求mysql表有主键的吗?
- MySQL基础知识点总结
- bad zipfile offset (local header sig)
- [Unity][ECS]学习笔记(三)
- Restful style
- Missed the golden three silver four, found a job for 4 months, interviewed 15 companies, and finally got 3 offers, ranking P7+
- Unity 从服务器加载AssetBundle资源写入本地内存,并将下载保存的AB资源从本地内存加载至场景
猜你喜欢

Dotnet uses crossgen2 to readytorun DLL to improve startup performance

装饰模式(Decorator)

Looking at jBPM from jbm3 to jbm5 and activiti

mysql打不开,闪退

Adapter mode

第六天 脚本与动画系统

Redis sentinel cluster main database failure data recovery ideas # yyds dry goods inventory #

Key summary V of PMP examination - execution process group

sqlcmd 连接数据库报错

How to view the web password saved by Google browser
随机推荐
JSON数据与List集合之间的正确转换
PHP curl forged IP address and header information code instance - Alibaba cloud
Methods for creating multithreads ---1 creating subclasses of thread class and multithreading principle
[Unity][ECS]学习笔记(一)
2020-10-27
Global exception handlers and unified return results
缓存之王Caffeine Cache,性能比Guava更强
Decorator
再見!IE瀏覽器,這條路由Edge替IE繼續走下去
Matplotlib属性及注解
谁知道在中信建投证券开户是不是安全的
PMP examination key summary VIII - monitoring process group (2)
我大抵是卷上瘾了,横竖睡不着!竟让一个Bug,搞我两次!
Bron filter Course Research Report
==And eqauls()
通过PyTorch构建的LeNet-5网络对手写数字进行训练和识别
[200 opencv routines] 213 Draw circle
纵观jBPM从jBPM3到jBPM5以及Activiti
Generate token
[Unity]内置渲染管线转URP