Using log4j 2 in a test framework

Source: Internet
Author: User
Tags log log xpath

Previous Test framework: http://www.cnblogs.com/tobecrazy/p/4553444.html

With Jenkins sustainable integration: http://www.cnblogs.com/tobecrazy/p/4529399.html

Playing log is one of the essential features of a test framework, and the trace test executes content that makes the test analysis easier and more regular to follow. The test log is further processed and the test results are automatically analyzed.

Java Project write log now generally use log4j 2

Log4j 2 is an open-source record log framework that is more efficient than log4j

More information: http://logging.apache.org/log4j/2.x/manual/index.html

First download the appropriate jar package and put it in the project:

Next, create the log class, using the

clazz.getcanonicalname () Get class name, get case name and page name and action name for future case execution
 PackageCom.log;ImportOrg.apache.logging.log4j.LogManager;ImportOrg.apache.logging.log4j.Logger; Public classLog {Private FinalClass<?>Clazz; PrivateLogger Logger; /**     *      * @paramClazz*/Log (Class<?>clazz) {         This. Clazz =Clazz;  This. Logger = Logmanager.getlogger ( This. Clazz); }    /**     * @authorYoung *@parammessage **/     Public voidinfo (String message) {Logger.info (Clazz.getcanonicalname ()+ ": " +message); }    /**     * @authorYoung *@parammessage*/     Public voidDebug (String message) {Logger.debug (Clazz.getcanonicalname ()+ ": " +message); }    /**     * @authorYoung *@parammessage*/     Public voiderror (String message) {Logger.error (Clazz.getcanonicalname ()+ ": " +message); }    /**     * @authorYoung *@parammessage*/     Public voidTrace (String message) {Logger.trace (Clazz.getcanonicalname ()+ ": " +message); }    /**     * @authorYoung *@parammessage*/     Public voidwarn (String message) {Logger.warn (Clazz.getcanonicalname ()+ ": " +message); }    /**     * @authorYoung *@parammessage*/     Public voidFatal (String message) {logger.fatal (Clazz.getcanonicalname ()+ ": " +message); }}

Next, you can call this class directly:

Package Com.log;public class Test {public static void main (string[] args) {//TODO auto-generated method Stublog log=new L  OG (test.class); Log.info ("This is My Test"), Log.debug ("This is a Debug"), Log.error ("This was an error"), Log.fatal ("This is A fatal "); Log.trace (" This is a Trace ");}}

Then run as application.

The results are as follows: Holy Shit,damn it actually error

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

The original is missing config

A copy of the Log4j2.xml file is prepared and placed under the package:

<?XML version= "1.0" encoding= "UTF-8"?><ConfigurationStatus= "WARN"><appenders>    <Consolename= "Console"Target= "System_out">        <Patternlayoutpattern= "%d{yyyy-mm-dd HH:mm:ss} [%t]%-5level%logger{36}-%msg%n"/>    </Console>    <Filename= "Log"FileName= "Logs/test.log"Append= "false">        <Patternlayoutpattern= "%d{yyyy-mm-dd HH:mm:ss. SSS}%-5level%class{36}%l%M-%msg%xex%n "/>    </File></appenders>    <Loggers>    <Loggername= "Com.dbyl.libarary.utils.Log" Level= "All">        <Appenderrefref= "Console"/>        <Appenderrefref= "Log"/>    </Logger>    <Root Level= "Trace">        <Appenderrefref= "Console"/>        <Appenderrefref= "Log"/>    </Root>  </Loggers></Configuration>
View Code

But it still doesn't work, it can't add parameters.

Plus:

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);

The result of the operation is as follows:

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

and logs the corresponding log file in the city directory

Of course, this is not perfect,log4j can be placed in the SRC directory, it is not necessary to specify the location

Next, put the log class in the test framework:

Add the appropriate code to the BasePage as follows:

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 ());p rotected 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 Butto n "); 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 Webele ment 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 ())); 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 Locato R = GetLocator (Mylocator.getelement ()); Boolean isPresent = false; webdriverwait wait = new webdriverwait (driver); isPresent = Wait.until (new expectedcondition<webelement> () {@ Overridepublic 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 > () {@Overridepublic webelement apply (webdriver driver) {try {return getelement (driver, locator);} catch (IOException e) {//TODO auto-generated catch Blocklog.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);}}

The corresponding code is also added to the UITest class:

/** *  */ Packagecom.dbyl.libarary.utils;ImportOrg.openqa.selenium.WebDriver;/** * @authorYoung **/ Public classUITest {webdriver driver; Log log=NewLog ( This. GetClass ());  PublicWebdriver Getdriver () {returndriver; }    /*** INIT Test Case * *@paramDriver*/     Public voidsetdriver (webdriver driver) { This. Driver =driver; }     Public voidInit (webdriver driver) {Log.info ("Start Webdriver");    Setdriver (driver); }    /*** Stop Webdriver * *@paramDriver*/     Public voidStop () {Log.info ("Stop Webdriver");    Driver.quit (); }}
View Code

The next is the time to witness miracles:

Run it: Log can clearly record what was done during the test

There is also a corresponding file log

Today's project: Http://pan.baidu.com/s/1kTqvzZx

Using log4j 2 in a test framework

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.