最近手头上闲下来了。想把工程中的暗门测试代码整理一下,看看能不能抽个工具出来。但是看到一堆堆性能测试,稳定性测试,鉴权测试。就觉得这啥代码呀,人要傻了。
所以就想着能不能重新写一下这块代码。
暂时有以下想法:
- 自定义注解
- 自动生成代码
- 插桩方式显示方法耗时
- 按需导出测试报告,崩溃报告(暂定java层崩溃日志,native日志算了吧)
- 。。。等等
其实第一点和第二点其实是一件事。。
有这个想法后脑子里很自然就蹦出greendao的自动生成代码方式。
翻看greendao代码。其生成代码是在gradle插件中,那就只能下载代码来看了。。
在greenDao生成代码核心类DaoGenerator中可以看到以下引用
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateNotFoundException;
greenDao中其实调用了freemarker工具,他是apache提供的一个模版生成工具。
freemarker官网
这第一篇文章就是将freemarker使用方法
try {
Configuration freemarker = freemarker();
//加载模版
template = freemarker.getTemplate("gx.ftl");
} catch (IOException e) {
e.printStackTrace();
}
private Configuration freemarker()throws IOException {
//实例化Configuration
Configuration config = new Configuration(Configuration.VERSION_2_3_31);
File dir = new File("src/main/resources/");
if (!dir.exists()) {
dir = new File("lib_freemarker/src/main/resources/");
}
if (dir.exists()) {
//设置模版文件的所在路径
config.setDirectoryForTemplateLoading(dir);
}
return config;
}
剩下的就是模版文件的编写了。按照我自己项目中的实际情况,配置参数可以包装成一个map传入模版中。而freemarker可以接受map。写一个简单例子的模版,实现图片检测的功能
//这里指传进来的对象。类似DataBinding的调用对象
<#-- @ftlvariable name="pro" type="com.winter.lib_freemarker.Pro" -->
package ${pro.defaultJavaPackage};
import com.test.DetectHelper;//测试类
import com.test.Result.Face;//测试类
public class ${pro.className} {
public void detect(String imgPath){
Face face = DetectHelper.detect(imgPath);//测试方法
}
}
剩下的就是文件的写入了
Pro pro = new Pro("com.winter.test", "MyTest");
File outputDir = new File("/Users/xxxx/Desktop/Code/Gx/lib_freemarker/build/test-out");
//创建文件
outputDir.mkdirs();
public void process(File outDirFile,Pro pro) {
Map<String, Object> root = new HashMap<>();
root.put("pro", pro);
//这个方法就是字符串拼接,造一个java文件出来
File file = toJavaFilename(outDirFile, pro.getDefaultJavaPackage(), pro.getClassName());
file.getParentFile().mkdirs();
try {
Writer writer = new FileWriter(file);
try {
//生成文件
template.process(root, writer);
//文件写入
writer.flush();
} finally {
writer.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
剩下的就是运行,然后可以在build文件夹下看到我们生成的文件
package com.winter.test;
import com.test.DetectHelper;
import com.test.Result.Face;
public class MyTest {
public void detect(String imgPath){
Face face = DetectHelper.detect(imgPath);
}
}
至此freemarker的简单使用就结束了。注释都写了。我觉得还是挺简单的。
其实主要就是模版文件的编写比较麻烦,需要花费大量的人力和时间。主要没有代码补全,好累。。。
第一篇就这样啦。改天再继续写我这个心血来潮,不知道能不能写出来的测试框架。。。