Search code examples
javacucumberjunit4bdd

@After and @Before annotation is not executing second method


I have declared 2 methods @after annotation but it will execute only the first method, it does not allow me to execute the second method. Please have a look at the below code

I want to execute 1 method every time for the exit of the browser. I want to execute the second method for failed test cases.

@Before
public void databaseLoading(Scenario scenario) {
    //System.out.println("Test Environment Set Up");
    System.out.println("\n------------------------------------------------     TEST ENVIRONMENT SET UP      ------------------------------------------------------------------------------\n");
    System.out.println("Executing Scenario :-> " + scenario.getName());
}

@After
public void browserTearDown()
{
    System.out.println("End the browser");
    driver.close();
 }

public void Screenshot(Scenario scenario) {
    // take the screenshot at the end of every test
    String location = ".\\target\\TakeScreenshot";
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MMM-yyyy hh-mm-ss", Locale.ENGLISH);
    Date date = new Date();
    File scrFile =
            ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
    // now save the screenshto to a file some place
    if (scenario.isFailed()) {
        try {
            FileUtils.copyFile(scrFile, new File(location + "\\" + dateFormat.format(date) + ".png"));
            System.out.println("Screenshot saved");
        } catch (IOException e) {
            System.out.println("Error in taking Screenshot --> " + e);
        }
    }
}

Method 'Screenshot(cucumber.api.Scenario)' is never used. This error message comes for the second method.


Solution

  • You only tagged browserTearDown() method.

    Add the @After tag to the Screenshot() method, as well:

    @After
    public void browserTearDown()
    {
        System.out.println("End the browser");
        driver.close();
    }
    
    @After
    public void Screenshot(Scenario scenario) {
       ...
    
    }