How to get the execution time of multiple methods in selenium java
Before executing the below code, make sure that pom is updated with the required dependencies or add required jars to Java build path.
We are using the Stopwatch of Apache Commons Lang to count the duration and reporter to log messages that will be included in the HTML reports generated by TestNG. Assuming that the TestNG plugin is installed in your IDE.
Add both dependencies to pom.xml of the Maven project or download the jars and add them to JAVA build path of the JAVA project.
<CODE>
import org.apache.commons.lang.time.StopWatch;
import org.testng.Reporter;
public class stopwatchtime extends StopWatch {
static StopWatch stopwatch = new StopWatch();
public static void timetaken(){
long x = stopwatch.getTime();
// Convert the result to a string
String numberAsString = Long.toString(x);
System.out.println(“Execution time for this method: “ + numberAsString + “ milliseconds \n”);
Reporter.log(“time taken to execute this method:”+ numberAsString +” milliseconds \n” );
}
public static void start(String methodname) {
stopwatch.start();
Reporter.log(methodname+”; \n”);
}
public static void stop(String methodname) {
stopwatch.stop();
Reporter.log(methodname+ “; \n”);
}
public static void reset(String methodname) {
stopwatch.reset();
Reporter.log(methodname+”; \n”);
}
}
}
</CODE>
Make sure that you have added this code to a separate class “stopwatchtime” inside the package where you want to perform these actions.
Now you can call these function multiple times in your main code inside same package:
stopwatchtime.reset(“timer reset”);
stopwatchtime.start(“timer started”);
stopwatchtime.stop(“timer stopped”);
stopwatchtime.timetaken();
To get the execution time of a specific method, call the above functions inside that method in the same fashion.
You can find the log messages in the generated TestNG report i.e. index.html or emailable-report.html
Happy Testing!