之前的测试框架:http://www.cnblogs.com/tobecrazy/p/4553444.html

配合Jenkins可持续集成:http://www.cnblogs.com/tobecrazy/p/4529399.html

这次demo的代码已经放到github:https://github.com/tobecrazy/Demo

打log是一个测试框架必备的功能之一,trace测试执行的内容,使测试分析更容易和有规律可循。进而进一步处理测试log,实现自动分析测试结果。

现在java项目写日志一般使用Log4j 2

log4j 2是一个开源的记录log的框架,比log4j 效率更高

更多内容:http://logging.apache.org/log4j/2.x/manual/index.html

首先下载相应的jar包,放到工程:

接下来创建Log类,使用

clazz.getCanonicalName() 获取类名字,为将来case执行获取case名和page名和action名
package com.log;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger; public class Log {
private final Class<?> clazz;
private Logger logger; /**
*
* @param clazz
*/
Log(Class<?> clazz) {
this.clazz = clazz;
this.logger = LogManager.getLogger(this.clazz);
} /**
* @author Young
* @param message
*
*/
public void info(String message) {
logger.info(clazz.getCanonicalName() + ": " + message);
} /**
* @author Young
* @param message
*/
public void debug(String message) {
logger.debug(clazz.getCanonicalName() + ": " + message);
} /**
* @author Young
* @param message
*/
public void error(String message) {
logger.error(clazz.getCanonicalName() + ": " + message);
} /**
* @author Young
* @param message
*/
public void trace(String message) {
logger.trace(clazz.getCanonicalName() + ": " + message);
} /**
* @author Young
* @param message
*/
public void warn(String message) {
logger.warn(clazz.getCanonicalName() + ": " + message);
} /**
* @author Young
* @param message
*/
public void fatal(String message) {
logger.fatal(clazz.getCanonicalName() + ": " + message);
}
}

接下来就可以直接调用这个类:

package com.log;

public class test {

	public static void main(String[] args) {
// TODO Auto-generated method stub
Log log=new Log(test.class);
log.info("this is my test");
log.debug("this is a debug");
log.error("this is an error ");
log.fatal("this is a fatal");
log.trace("this is a trace");
} }

  然后, run as application 吧

结果如下: holy shit,damn it 居然报错

ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.
23:52:47.679 [main] ERROR com.log.test - com.log.test: this is an error
23:52:47.680 [main] FATAL com.log.test - com.log.test: this is a fatal

原来是缺少config

于是乎准备一份log4j2.xml文件,放在该package下:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
<File name="log" fileName="logs/test.log" append="false">
<PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n"/>
</File>
</Appenders>
<Loggers>
<Logger name="com.dbyl.libarary.utils.Log" level="all">
<AppenderRef ref="Console"/>
<AppenderRef ref="log"/>
</Logger>
<Root level="trace">
<AppenderRef ref="Console"/>
<AppenderRef ref="log"/>
</Root>
</Loggers>
</Configuration>

但是依然不行,没法加参数

加上:

File config=new File("C:/Users/Young/workspace/Log4j/src/com/log/log4j2.xml");
ConfigurationSource source = new ConfigurationSource(new FileInputStream(config),config);
Configurator.initialize(null, source);

  妥妥的 , 运行结果如下:

2015-06-07 00:06:31 [main] INFO com.log.test - com.log.test: this is my test
2015-06-07 00:06:31 [main] DEBUG com.log.test - com.log.test: this is a debug
2015-06-07 00:06:31 [main] ERROR com.log.test - com.log.test: this is an error
2015-06-07 00:06:31 [main] FATAL com.log.test - com.log.test: this is a fatal
2015-06-07 00:06:31 [main] TRACE com.log.test - com.log.test: this is a trace

并且logs目录下生城相应的log文件

当然,这并不完美,log4j可以放在src目录下,这要就不需要指定位置

接下来把这个log类放在测试框架里:

在basePage加入相应的代码,如下:

package com.dbyl.libarary.utils;

import java.io.IOException;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait; public class BasePage { protected WebDriver driver;
protected String[][] locatorMap;
protected Log log= new Log(this.getClass()); protected BasePage(WebDriver driver) throws IOException {
this.driver = driver;
locatorMap = ReadExcelUtil.getLocatorMap();
} protected void type(Locator locator, String values) throws Exception {
WebElement e = findElement(driver, locator);
log.info("type value is: "+ values);
e.sendKeys(values);
} protected void click(Locator locator) throws Exception {
WebElement e = findElement(driver, locator);
log.info("click button");
e.click();
} protected void clickAndHold(Locator locator) throws IOException {
WebElement e = findElement(driver, locator);
Actions actions = new Actions(driver);
actions.clickAndHold(e).perform();
} public WebDriver getDriver() {
return driver;
} public void setDriver(WebDriver driver) {
this.driver = driver;
} public WebElement getElement(Locator locator) throws IOException {
return getElement(this.getDriver(), locator);
} /**
* get by parameter
*
* @author Young
* @param driver
* @param locator
* @return
* @throws IOException
*/
public WebElement getElement(WebDriver driver, Locator locator)
throws IOException {
locator = getLocator(locator.getElement());
WebElement e;
switch (locator.getBy()) {
case xpath:
log.debug("find element By xpath");
e = driver.findElement(By.xpath(locator.getElement()));
break;
case id:
log.debug("find element By id");
e = driver.findElement(By.id(locator.getElement()));
break;
case name:
log.debug("find element By name");
e = driver.findElement(By.name(locator.getElement()));
break;
case cssSelector:
log.debug("find element By cssSelector");
e = driver.findElement(By.cssSelector(locator.getElement()));
break;
case className:
log.debug("find element By className");
e = driver.findElement(By.className(locator.getElement()));
break;
case tagName:
log.debug("find element By tagName");
e = driver.findElement(By.tagName(locator.getElement()));
break;
case linkText:
log.debug("find element By linkText");
e = driver.findElement(By.linkText(locator.getElement()));
break;
case partialLinkText:
log.debug("find element By partialLinkText");
e = driver.findElement(By.partialLinkText(locator.getElement()));
break;
default:
e = driver.findElement(By.id(locator.getElement()));
}
return e;
} public boolean isElementPresent(WebDriver driver, Locator myLocator,
int timeOut) throws IOException {
final Locator locator = getLocator(myLocator.getElement());
boolean isPresent = false;
WebDriverWait wait = new WebDriverWait(driver, 60);
isPresent = wait.until(new ExpectedCondition<WebElement>() {
@Override
public WebElement apply(WebDriver d) {
return findElement(d, locator);
}
}).isDisplayed();
return isPresent;
} /**
* This Method for check isPresent Locator
*
* @param locator
* @param timeOut
* @return
* @throws IOException
*/
public boolean isElementPresent(Locator locator, int timeOut)
throws IOException {
return isElementPresent(driver,locator, timeOut);
} /**
*
* @param driver
* @param locator
* @return
*/
public WebElement findElement(WebDriver driver, final Locator locator) {
WebElement element = (new WebDriverWait(driver, locator.getWaitSec()))
.until(new ExpectedCondition<WebElement>() { @Override
public WebElement apply(WebDriver driver) {
try {
return getElement(driver, locator);
} catch (IOException e) {
// TODO Auto-generated catch block
log.error("can't find element "+locator.getElement());
return null;
} } });
return element; } public Locator getLocator(String locatorName) throws IOException { Locator locator;
for (int i = 0; i < locatorMap.length; i++) {
if (locatorMap[i][0].endsWith(locatorName)) {
return locator = new Locator(locatorMap[i][1]);
}
} return locator = new Locator(locatorName); }
}

  在UITest类也加入相应的代码:

/**
*
*/
package com.dbyl.libarary.utils; import org.openqa.selenium.WebDriver; /**
* @author Young
*
*/
public class UITest {
WebDriver driver;
Log log=new Log(this.getClass()); public WebDriver getDriver() {
return driver;
} /**
* init test case
*
* @param driver
*/
public void setDriver(WebDriver driver) {
this.driver = driver;
} public void init(WebDriver driver) {
log.info("Start WebDriver");
setDriver(driver);
} /**
* stop webdriver
*
* @param driver
*/
public void stop() {
log.info("Stop WebDriver");
driver.quit(); } }

接下来就是见证奇迹的时候:

运行一下:log能够清晰记录测试时所做的内容

也有相应的file log

今天的工程下载地址:http://pan.baidu.com/s/1kTqvzZx

在测试框架中使用Log4J 2的更多相关文章

  1. selenium 测试框架中使用grid

    之前的测试框架:http://www.cnblogs.com/tobecrazy/p/4553444.html 配合Jenkins可持续集成:http://www.cnblogs.com/tobecr ...

  2. JAVA使用log4j(另SSM框架中使用log4j)

    1.引入jar包 log4j-1.2.13.jar 2.src下建立配置文件:log4j.properties #不+All,只写后一种LOG log4j.rootLogger =ALL,system ...

  3. SSH框架中配置log4j的方法

    SSH框架中使用log4j的方便之处 1. 动态的改变记录级别和策略,即修改log4j.properties,不需要重启Web应用,这需要在web.xml中设置一下.2. 把log文件定在 /WEB- ...

  4. python nose测试框架中使用allure_report框架

    在使用nose自带的xunit生成xml文件生成测试报告后,领导说报告不够炫,没有百分比效果,且在web自动化时的截图不美观,html很多情况下没有显示图片(nose框架截图方法这里),正好,allu ...

  5. SSI框架中配置log4j

    事实上主要是log4j配置,跟SSI关系不大. web.xml中加入 <context-param> <param-name>log4jConfigLocation</p ...

  6. 自己测试项目中的log4j配置

    日志生成的位置在项目名下 主要记录的是这样配置,日志的生成的地方 下边是配置文件的内容 log4j.rootLogger=WARN, stdout, file log4j.appender.stdou ...

  7. Unit Test测试框架中的测试的执行顺序

    [ClassInitialize()] [ClassCleanup()] [TestInitialize()] [TestMethod] [TestCleanup()] 在执行一个或多个[TestMe ...

  8. 【Python】【unittest】unittest测试框架中setup,teardown与setupclass,teardownclass的区别

    # -*- coding:utf-8 -*- import unittest def runTest(testcaseclass,testcase=[]): suite = unittest.Test ...

  9. 为测试框架model类自动生成xml结果集

    问题:有大量类似于theProductId这样名字的字符串需要转换成the_product_id这种数据库column名的形式. 思路:见到(见)大写字母(缝)就插入(插)一个“_”字符(针)进去,最 ...

随机推荐

  1. IT行业的技术类岗位分为许多种,如何判断自己适合哪种?

    A.硬件工程师B.软件工程师C.UI设计师D.仿真工程师E.ERP工程师F.集成工程师G.系统架构设计师H.数据库工程师I.网络管理员J.网络安全工程师K.网站架构设计师L.网页设计M.Flash设计 ...

  2. C#进阶系列——DDD领域驱动设计初探(五):AutoMapper使用

    前言:前篇搭建了下WCF的代码,就提到了DTO的概念,对于为什么要有这么一个DTO的对象,上章可能对于这点不太详尽,在此不厌其烦再来提提它的作用: 从安全上面考虑,领域Model都带有领域业务,让Cl ...

  3. 1125MySQL Sending data导致查询很慢的问题详细分析

    -- 问题1 tablename使用主键索引反而比idx_ref_id慢的原因EXPLAIN SELECT SQL_NO_CACHE COUNT(id) FROM dbname.tbname FORC ...

  4. 理解C# 4 dynamic(1) - var, object, dynamic的区别以及dynamic的使用

    阅读目录: 一. 为什么是它们三个 二. 能够任意赋值的原因 三. dynamic的用法 四. 使用dynamic的注意事项 一. 为什么是它们三个? 拿这三者比较的原因是它们在使用的时候非常相似.你 ...

  5. elipse 从eclipse导入maven项目

    1. 使用Eclipse通过Svn导入项目 2.cmd 在项目目录下执行 mvn eclipse:eclipse 3. 然后在项目上点击右键 configure ->convert to mav ...

  6. IOS在自己网站发布APP(企业版$299上线流程)

    最近刚上线一个企业内部应用,前期准备账号和后期上线过程发现网络上的资源不是非常全面,在这里写给大家分享一下我的发布过程 首先是企业账号的申请我们企业账号前前后后一共花了16天时间,由于公司各方面都非常 ...

  7. python脚本实现scp上传下载功能

    普通版本 1 # -*- coding:utf-8 -*- import paramiko,os,sys,time port = 22 user = 'root' def ssh_scp_put(ip ...

  8. 用VS开发PHP扩展

    开发前准备工作: VS(我用的2013) Cygwin(下载地址:http://www.cygwin.com/) 搭载了php运行环境的IIS7.5 (用来测试) php编译后的程序和编译前的源码,我 ...

  9. UIDynamic-附着行为:UIAttachmentBehavior

    直接上代码: // // YFAttachmentBehaviorViewController.m // BigShow1949 // // Created by apple on 16/8/25. ...

  10. mui消息框alert,confirm,prompt,toast

    <script type="text/javascript" charset="utf-8"> //mui初始化 mui.init({ swipeB ...