Jump to content
We've recently updated our Privacy Statement, available here ×
  • Usage of JVM addShutdownHook in cucumber selenium testng automation to send latest cucumber or extent reports in email


    Hi, In this post, we can see how to use JVM shut down hook with in cucumber Hooks. 

    What is JVM shut down hook ?
    (Definition credits : geeksforgeeks.org)

    A special construct that facilitates the developers to add some code that has to be run when the
    Java Virtual Machine (JVM) is shutting down is known as the Java shutdown hook. 


    Begin with some interesting questions ! 
    1) Did you ever think of refreshing a folder in java coding to send latest run cucumber report or
         extent report ? 
    2) Did you keep your email notification code in cucumber After or AfterAll hook and tried
         sending email but ended-up with old report in mail inbox ? 
    3) How did you solve this problem with Cucumber, TestNG integration ? 

    Perhaps! There might be other solutions and could be better ones. 
    My approach was, effectively make use of JVM shut down hook with in cucumber AfterAll hook to have the latest run report attached and sent over the email. 

    It started with, 
    What is cucumber AfterAll hook ? 

    AfterAll is a cucumber hook that run after all scenarios have been executed.

    @AfterAllpublic static void afterAll() {    // Runs after all scenarios}

    JVM Shutdown hook basic example: 
    In the below program, there are two print statements.

    By using addShutdownHook JVM would print  "This text prints before shutdown!" firstly and at the time JVM shut down it prints "Shutdown Hook is running and this prints at last!"

    That is, statements inside run() method executes at the very end.  

    public class ShutDownHook{  public static void main(String[] args)  {     Runtime.getRuntime().addShutdownHook(new Thread()    {      public void run()      {        System.out.println("Shutdown Hook is running and this prints at last!");      }    });    System.out.println("This text prints before shutdown!");  }}

    Below is the combined implementation of @AfterAll cucumber hook and JVM addShutdownHook. 
    In the run() method, keep the email triggering code so the selenium execution always picks the latest report to be sent in the mail. It pretty much worked through jar execution too. 

    package parallel;import java.net.InetAddress;import java.net.UnknownHostException;import io.cucumber.java.After;import io.cucumber.java.AfterAll;import io.cucumber.java.Before;import io.cucumber.java.Scenario;public class Hooks {	@Before(order = 0)	public void before(Scenario scenaio) throws Exception {		DriverFactory.setDriver();		System.out.println("Current Thread Name:" + Thread.currentThread().getName());		System.out.println("Current Thread ID:" + Thread.currentThread().getId());	}	@After(order = 0)	public void after() throws Exception {		DriverFactory.closeDriver();	}	@AfterAll(order = 0)	public static void afterAll() throws UnknownHostException {		System.out.println("AfterAll - with order=0");		InetAddress localhost = InetAddress.getLocalHost();		System.out.println("System IP Address : " + (localhost.getHostAddress()).trim());		Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {			@Override			public void run() {				System.out.println("Shutdown Hook is running and this text prints before JVM shut downs!");			}		}));		System.out.println("This text prints before Shutdown hook");	}}


    Eclipse logs: 
    [RemoteTestNG] detected TestNG version 7.7.0SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".SLF4J: Defaulting to no-operation (NOP) logger implementationSLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.@LoginFeature @ForgotPasswordScenario: Forgot password link verification       # parallel/Login.feature:16@LoginFeature @LoginScenario: Login to Orange HRM                       # parallel/Login.feature:9Jun 11, 2023 1:01:23 AM org.openqa.selenium.remote.service.DriverService$Builder getLogOutputINFO: Driver logs no longer sent to console by default; https://www.selenium.dev/documentation/webdriver/drivers/service/#setting-log-outputJun 11, 2023 1:01:23 AM org.openqa.selenium.remote.service.DriverService$Builder getLogOutputINFO: Driver logs no longer sent to console by default; https://www.selenium.dev/documentation/webdriver/drivers/service/#setting-log-outputCurrent Thread Name:TestNG-PoolService-0Current Thread ID:16Current Thread Name:TestNG-PoolService-1Current Thread ID:17  Given User is on login page                       # parallel.LoginStepDef.user_is_on_login_page()  When User enters username "Admin"                 # parallel.LoginStepDef.user_enters_username(java.lang.String)  Given User is on login page                     # parallel.LoginStepDef.user_is_on_login_page()  Then User verifies Forgot password link display # parallel.LoginStepDef.user_verifies_forgot_password_link_display()  And User enters password "Admin123"               # parallel.LoginStepDef.user_enters_password(java.lang.String)  And User clicks on Login button                   # parallel.LoginStepDef.user_clicks_on_login_button()Navigation to home page  Then User should navigate to Orange HRM home page # parallel.LoginStepDef.user_should_navigate_to_orange_hrm_home_page()AfterAll - with order=0System IP Address : 192.168.1.8This text prints before Shutdown hook┌──────────────────────────────────────────────────────────────────────────┐│ View your Cucumber Report at:                                            ││ https://reports.cucumber.io/reports/213e45d0-8053-4753-b2c4-78f40d98bd71 ││                                                                          ││ This report will self-destruct in 24h.                                   ││ Keep reports forever: https://reports.cucumber.io/profile                │└──────────────────────────────────────────────────────────────────────────┘PASSED: io.cucumber.testng.AbstractTestNGCucumberTests.runScenario("Login to Orange HRM", "Login page validations")        Runs Cucumber ScenariosPASSED: io.cucumber.testng.AbstractTestNGCucumberTests.runScenario("Forgot password link verification", "Login page validations")        Runs Cucumber Scenarios===============================================    Default test    Tests run: 1, Failures: 0, Skips: 0==============================================================================================Default suiteTotal tests run: 2, Passes: 2, Failures: 0, Skips: 0===============================================Shutdown Hook is running and this text prints before JVM shut downs!

    I hope this helped you a bit! If you like it, please do Subscribe my YouTube channel for interesting updates.

    User Feedback

    Recommended Comments

    There are no comments to display.



    Guest
    This is now closed for further comments

×
×
  • Create New...