Method interceptors in junit

Method interceptors are used to write custom code before and after calling the test method in JUnit. Note that @Before and @After annotations can not be used in this case as they can not be used to catch the exceptions in test method. In below example, we have declared one rule – MyMethodRule that can be used to intercept the test method.
 
package seleniumtests;

import org.junit.Assert;
import org.junit.Rule;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import rules.MyMethodRule;

public class MethodInterceptorTest {

    public WebDriver driver=new FirefoxDriver();

    @Rule
    public MyMethodRule m = new MyMethodRule(driver);

    @Test
    public void verifyTitle(){
        driver.get("https://www.softpost.org");
        Assert.assertTrue(driver.getTitle().contains("My Tuts"));
    }

}

Below code shows the implementation of Method Rule to intercept the test method. Note that whenever the exception is thrown by the test, screenshot is taken and image is saved on system. Without method rule, we will have to wrap all test methods inside try and catch block.
 
package rules;

import org.apache.commons.io.FileUtils;
import org.junit.rules.MethodRule;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import seleniumtests.BaseTest;

import java.io.File;
import java.io.FileOutputStream;

/**
 * Created by Sagar on 26-06-2016.
 */
public class MyMethodRule implements MethodRule {
    WebDriver driver;
    public MyMethodRule(WebDriver driver){
        this.driver = driver;
    }
    public Statement apply(final Statement statement, final FrameworkMethod frameworkMethod, final Object o) {
        return new Statement() {
            @Override
            public void evaluate() throws Throwable {
                try {
                    System.out.println("Executing method" + statement.toString());
                    statement.evaluate();
                } catch (Throwable t) {
                    captureScreenshot(frameworkMethod.getName());
                    throw t;
                }finally {
                    driver.close();
                    driver.quit();
                }
            }

            public void captureScreenshot(String fileName) {
                File f = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
                try {
                    FileUtils.copyFile(f, new File("C:\Users\Sagar\IdeaProjects\JunitProject\target\abc.png"));
                }catch (Exception ex){
                    System.out.println("exception " +ex.getMessage());
                }
            }
        };
    }
}

Web development and Automation testing

solutions delivered!!