在Java中直接操作ant来测试和生成测试报告

Ant是大家熟悉的构建工具,一般情况下,大家都是使用build.xml文件来配置使用Ant,这样的Ant已经是十分强大的。但有些怪异的场景需求特殊,你可能希望在自己的java程序中直接使用Ant已经准备好的功能强大的轮子,比如:在你的web应用中嵌入各种Junit测试,通过Jsp页面控制集成测试,生成测试报告后在web直接展示。你可能可以说,我完全可以通过代码自己实现,生成报告也最多自己在扩展封装下而已。但是Ant已经提供测试,报告各种强大的功能,为何我们不自己使用呢。我们只是不想只在构建的时候做这些事,而是在我们的进程中使用Ant.

令我们高兴的是,Ant是使用Java开发的,对我们,只是引入了几个Ant的jar包就可以使用了。

说到了测试,这次是做一个自动化测试框架,我希望达到上面所说的怪异需求。那我最需要的是什么,是的,通过ant执行junit测试,并按照模板输出测试报告。在参考了Ant的API后,我折腾出了下面这段代码.

//所有的Task都必须设置一个Project对象,可以共用一个Project.

private Project prj = new Project();

public void simpleJunitTest(String testClassName, File reportXmlDir, boolean isFork) throws Exception {

JUnitTask task = new JUnitTask();

initJunitTask(isFork, task);

JUnitTest test = new JUnitTest(testClassName);

task.addTest(test);

test.setTodir(reportXmlDir);

task.execute();

}

public void callBatchJunitTest(String includes, boolean isFork, FileSet fs, File reportXmlDir) throws Exception {

JUnitTask task = new JUnitTask();

initJunitTask(isFork, task);

BatchTest btest = task.createBatchTest();

btest.addFileSet(fs);

btest.setTodir(reportXmlDir);

task.execute();

}

private void initJunitTask(boolean isFork, JUnitTask task) {

task.setProject(prj);

task.setFork(isFork);

JUnitTask.SummaryAttribute printSummary = new JUnitTask.SummaryAttribute();

printSummary.setValue("yes");

task.setPrintsummary(printSummary);

task.setHaltonerror(false);

task.setHaltonfailure(false);

task.setFailureProperty("junit.failure");

task.setErrorProperty("junit.error");

task.addFormatter(createFormatterElement("xml"));

}

private FormatterElement createFormatterElement(String value) {

FormatterElement fe = new FormatterElement();

FormatterElement.TypeAttribute typeAttribute = new FormatterElement.TypeAttribute();

typeAttribute.setValue(value);

fe.setType(typeAttribute);

return fe;

}

public void createJunitReport(File reportXmlDir, String tempDir, File reportHtmlDir, File styleDir) throws Exception {

XMLResultAggregator task = new XMLResultAggregator();

task.setProject(prj);

FileSet fs = new FileSet();

fs.setDir(reportXmlDir);

fs.setIncludes("TEST-*.xml");

task.addFileSet(fs);

task.setTodir(reportXmlDir);

//必须设置,否则会空指针异常

prj.setProperty("java.io.tmpdir", tempDir);

AggregateTransformer aggregateTransformer = task.createReport();

aggregateTransformer.setTodir(reportHtmlDir);

AggregateTransformer.Format format = new AggregateTransformer.Format();

format.setValue(AggregateTransformer.FRAMES);

aggregateTransformer.setFormat(format);

aggregateTransformer.setStyledir(styleDir);

task.execute();

}

通过上面的方法就可以在java中直接调用ant提供的junit test,并生成最终报告。

对于Ant的使用,还有很多,一下是我收集到的一些,有些时候在一些场合应该很不错。下面贴的是完整的类。这边还有说明下,需要的jar包在ANT_HOME/lib下都有。大家按照需要导入即可。

完整的类:(。。。部分为上面已经贴出部分)

AntCallSample.java

package com.eta02913.antcall;

import org.apache.tools.ant.DirectoryScanner;

import org.apache.tools.ant.Project;

import org.apache.tools.ant.taskdefs.*;

import org.apache.tools.ant.taskdefs.optional.junit.*;

import org.apache.tools.ant.types.FileSet;

import org.apache.tools.ant.types.FilterSet;

import org.apache.tools.ant.types.PatternSet;

import org.apache.tools.ant.types.ZipScanner;

import org.apache.tools.zip.*;

import java.io.File;

import java.io.IOException;

import java.util.Enumeration;

/**

* Created by IntelliJ IDEA.

* User: eta02913

* Date: 11-3-28

* Time: 上午9:07

* To change this template use File | Settings | File Templates.

*/

public class AntCallSample {

//所有的Task都必须设置一个Project对象,可以共用一个Project.

private Project prj = new Project();

public void mkDir(String fileName) {

mkdir(new File(fileName));

}

public void mkdir(File file) {

Mkdir mkdir = new Mkdir();

mkdir.setProject(prj);

mkdir.setDir(file);

mkdir.execute();

}

public void deleteDir(String dirPath) {

deleteDir(new File(dirPath));

}

public void deleteDir(File dir) {

Delete delete = new Delete();

delete.setProject(prj);

delete.setDir(dir);

delete.execute();

}

public void deleteFile(File file) {

Delete delete = new Delete();

delete.setProject(prj);

delete.setFile(file);

delete.execute();

}

public void copyFileToDir(File file, File toDir, boolean isOverWrite) {

Copy copy = new Copy();

copy.setProject(prj);

copy.setFile(file);

copy.setTodir(toDir);

copy.setOverwrite(isOverWrite);

copy.execute();

}

/**

* 复制文件并替换文件中的内容

*

* @param fromDir 待复制的文件夹

* @param toDir 目标文件夹

* @param includes 包含哪些文件

* @param token 文件中待替换的字符串

* @param value 替换后的字符串

*/

public void copyAndReplace(File fromDir, File toDir, String includes, String token, String value) {

Copy copy = new Copy();

copy.setEncoding("UTF-8");

copy.setProject(prj);

copy.setTodir(toDir);

FileSet fileSet = new FileSet();

fileSet.setDir(fromDir);

fileSet.setIncludes(includes);

copy.addFileset(fileSet);

FilterSet filter = copy.createFilterSet();

filter.addFilter("eosapp_name", "app1");

copy.execute();

}

public void move(File file, File toDir) {

Copy copy = new Move();

copy.setProject(prj);

copy.setFile(file);

copy.setTodir(toDir);

copy.execute();

}

public void rename(File oldFile, File newFile) {

Copy copy = new Copy();

copy.setProject(prj);

copy.setFile(oldFile);

copy.setTodir(newFile);

copy.execute();

}

/**

* 文件集合

*

* @param dir

* @param includes 包含的文件;表达式,使用,或者空格分隔字符串,“**”代表所有文件或目录,“*.*”代表说有文件, “*.java”代表所有扩展名为java的文件

* @param excludes 排除的文件:表达式,使用,或者空格分隔字符串,“**”代表所有文件或目录,“*.*”代表说有文件, “*.java”代表所有扩展名为java的文件

*/

public void createFileSet(File dir, String includes, String excludes) {

FileSet fs = new FileSet();

fs.setProject(prj);

fs.setDir(dir);

if (isEmpty(includes)) {

includes = "**/*.*";//默认包含所有文件

}

fs.setIncludes(includes);

if (!isEmpty(excludes)) {

fs.setExcludes(excludes);

}

}

private boolean isEmpty(String str) {

return str == null || "".equals(str);

}

public void scanDir(File baseFile) {

DirectoryScanner ds = new DirectoryScanner();

ds.setBasedir(baseFile);

ds.scan();

if (ds.getIncludedFilesCount() > 0) {

String[] includeFiles = ds.getIncludedFiles();

for (String file : includeFiles) {

System.out.println(file);

}

}

}

public void zipFile(FileSet fileSet, File destFile) {

Zip zip = new Zip();

zip.setProject(prj);

zip.setDestFile(destFile);

zip.addFileset(fileSet);

zip.execute();

}

public void jarFile(FileSet fileSet, File destFile) {

Jar jar = new Jar();

jar.setProject(prj);

jar.setDestFile(destFile);

jar.addFileset(fileSet);

jar.execute();

}

public void expandAllFile(File srcFile, File destDir, boolean isOverWrite) {

Expand expand = new Expand();

expand.setProject(prj);

expand.setSrc(srcFile);

expand.setOverwrite(isOverWrite);

expand.setDest(destDir);

expand.execute();

}

public void expanFileWithPattern(File srcFile, File destDir, PatternSet patternset, boolean isOverWrite) {

Expand expand = new Expand();

expand.setProject(prj);

expand.setSrc(srcFile);

expand.setOverwrite(isOverWrite);

expand.setDest(destDir);

expand.addPatternset(patternset);

expand.execute();

}

public void createPatternSet(String includes, String excludes) {

PatternSet patternset = new PatternSet();

patternset.setProject(prj);

if (!isEmpty(includes)) {

patternset.setIncludes(includes);

}

if (!isEmpty(excludes)) {

patternset.setExcludes(excludes);

}

}

public void readZipFile(File zipFile) {

ZipFile zipfile = null;

try {

zipfile = new ZipFile(zipFile);

Enumeration entries = zipfile.getEntries();

while (entries.hasMoreElements()) {

ZipEntry entry = (ZipEntry) entries.nextElement();

if (entry.isDirectory()) {

System.out.println("Directory: " + entry.getName());

} else {

System.out.println("file: " + entry.getName());

}

}

} catch (IOException e) {

e.printStackTrace();

} finally {

if (zipfile != null) {

try {

zipfile.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

public void scanZipFile(File srcFile) {

ZipScanner scan = new ZipScanner();

scan.setSrc(srcFile);

// scan.setIncludes(new String[]);

scan.scan();

String dirs[] = scan.getIncludedDirectories();

String files[] = scan.getIncludedFiles();

}

public void simpleJunitTest(String testClassName, File reportXmlDir, boolean isFork) throws Exception {

。。。

}

public void callBatchJunitTest(String includes, boolean isFork, FileSet fs, File reportXmlDir) throws Exception {

。。。

}

private void initJunitTask(boolean isFork, JUnitTask task) {

。。。

}

private FormatterElement createFormatterElement(String value) {

。。。

}

public void createJunitReport(File reportXmlDir, String tempDir, File reportHtmlDir, File styleDir) throws Exception {

。。。 }

}

更多的方法,可以自行参考ant的api或者源码。ant的api在官网是不提供查询的,而是在下载的完整ant包里有提供。

ant java 返回,在Java中直接操作ant回测试和生成测试报告相关推荐

  1. java返回fail_Java集合中的fail-fast(快速失败)机制详解

    简介 我们知道Java中Collection接口下的很多集合都是线程不安全的, 比如 java.util.ArrayList不是线程安全的, 因此如果在使用迭代器的过程中有其他线程修改了list,那么 ...

  2. Java 8 Stream Api 中的 skip 和 limit 操作

    点击上方蓝色"程序猿DD",选择"设为星标" 回复"资源"获取独家整理的学习资料! 1. 前言 Java 8 Stream API 中的sk ...

  3. 聚合中返回source_Java 8 中的 Streams API 详解—— Streams 的背景以及 Java 8 中的使用详解...

    为什么需要 Stream Stream 作为 Java 8 的一大亮点,它与 java.io 包里的 InputStream 和 OutputStream 是完全不同的概念.它也不同于 StAX 对 ...

  4. 转载:JAVA 操作 Ant API

    2019独角兽企业重金招聘Python工程师标准>>> Java调用Ant API用法  用法 API 调用 JAVA  Ant是Java程序员的一个好的工具,主要可以帮助程序员进行 ...

  5. java jedis使用_Java中使用Jedis操作Redis

    Java中使用Jedis操作Redis 使用Java操作Redis需要jedis-2.1.0.jar,下载地址:http://files.cnblogs.com/liuling/jedis-2.1.0 ...

  6. android java写文件_Android中文件的读写(一)----流操作

    因为自己的Java基本功不扎实,所以这篇文章主要介绍Java中的流操作,让自己再学习一下. Java IO Java IO中用于读写文件的四个抽象类:Reader,Writer,InputStream ...

  7. java中注解操作redis_spring boot —— redis 缓存注解使用教程

    spring boot -- redis 缓存注解使用教程 依赖 在pom文件添加如下依赖 org.springframework.boot spring-boot-starter-data-redi ...

  8. java redis 过期_Redis中的键值过期操作

    1.过期设置 Redis 中设置过期时间主要通过以下四种方式: expire key seconds:设置 key 在 n 秒后过期: pexpire key milliseconds:设置 key ...

  9. java时间设置_JAVA中的时间操作

    java中的时间操作不外乎这四种情况: 1.获取当前时间 2.获取某个时间的某种格式 3.设置时间 4.时间的运算 好,下面就针对这四种情况,一个一个搞定. 一.获取当前时间 有两种方式可以获得,第一 ...

最新文章

  1. zookeeper 进入客户端_对 zookeeper 和 dubbo 问题总结
  2. android 封装状态页面,Android 缺省页状态切换方案
  3. 亚马逊瞄准大数据 欲在汽车行业抢占一席之地
  4. The way of Webpack learning (II.) -- Extract common code(多页面提取公共代码)
  5. VTK:vtkTupleInterpolator 插值用法实战
  6. allegro 16.6/17.4 中如何将实心焊盘显示为空心焊盘
  7. Oracle入门(十二E)之视图操作
  8. CV Code | 本周新出计算机视觉开源代码汇总(含自动驾驶目标检测、医学图像分割、风格迁移、语义分割、目标跟踪等)...
  9. SQL Server FOR XML PATH 语句的应用---列转行
  10. cocos2d-x之读取xml文件
  11. 使用ByteArray及AMF来提高Data Object的操作效率
  12. zookeeper分布式协调服务的使用一
  13. iOS开源弹幕库BarrageRenderer
  14. VisionPro如何引用VPP?
  15. Julia会是超越Python的存在吗
  16. MTF SFR 简介
  17. 债券数据集:绿色债券数据集、历时新发、发行债券、DCM定价估值四大指标数据
  18. 制作可独立分发的Android模拟器
  19. TxtView 手机文本阅读器
  20. 对于计算机学科的认识和一些感想

热门文章

  1. eclipse设置黑色背景
  2. php strtotime,PHP strtotime()函数
  3. 《C语言进阶剖析》1.C语言开发环境搭建与入门
  4. 机器学习在自动驾驶中的应用-以百度阿波罗平台为例【上】
  5. KMeans秘籍之如何确定K值
  6. CISCO认证体系简介
  7. python环境复制_python 环境
  8. 基于PyTorch+HAN实现中文情感分类任务
  9. 微软新技术展望大会 -- 比尔·盖茨演讲全文及问答
  10. C++贪心算法:蒜头君的钱包