Most Viewed Pages

6.7.16

Java Code Snippets

Some random code snippets...

Running JavaScript via WebDriver -


JavascriptExecutor jsRunner = (JavascriptExecutor) driver;

// This will get us the name of the browser on which the test is running
String jsString = "return navigator.appCodeName";
System.out.println ("BrowserName = " + jsRunner.executeScript(jsString));

Code to get the text of all the links on a web page -

List<WebElement> allLinks = driver.findElements(By.tagName("a"));
for (WebElement link : allLinks){
     System.out.println("Link text = " + link.getText());
}

File copy - just ensure that the folder path has a \\ in the end, otherwise, the files wont be copied/deleted and even strange-ly, there wont be any errors!

    //Function to copy all the files in a dir, but will not replace if the file already exists
    public void copyAllFilesToDir(String sourceDir, String destinationDir){
        String fileName = null;

        File folder = new File(sourceDir);
        File[] listOfFiles = folder.listFiles();
        //loop through all the files in the dir
        for (int i =0; i < listOfFiles.length; i++){
            //check if the item is a file or a folder
            if(listOfFiles[i].isFile()){
                fileName = listOfFiles[i].getName();
                copyFile(sourceDir + fileName, destinationDir + fileName);
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.getMessage();
                }
            }
        }
    }

    //Function to delete all files in a dir
    public void deleteAllFiles(String dirPath){

        File folder = new File(dirPath);
        File[] listOfFiles = folder.listFiles();
        for (int i = 0; i < listOfFiles.length; i ++){
            if (listOfFiles[i].isFile()){
                if(listOfFiles[i].delete()){
                    System.out.println("file deleted -" + listOfFiles[i].getName());
                }else {
                    System.out.println("could NOT delete file -" + listOfFiles[i].getName());
                }
            }
        }
    }

    //Function to copy one file at a time, does not overwrite/replace existing files
    public void copyFile(String sourceFilePath,String destinationFilePath){
        File sourceFile = new File(sourceFilePath);
        File destinationFile = new File(destinationFilePath);
        try {
            FileUtils.copyFile(sourceFile, destinationFile);
        } catch (IOException e) {
            e.getMessage();
        }
    }

JBehave Configuration for BDD


Custom Configurations for JBehave

1.   Meta Filters -

·      Meta filtering is most useful when we want to perform selective running of stories/scenarios.
To enable filtering in JBehave based on Meta tags, just add the following 3 lines in the MyStories class, under the Constructor [MyStories() - created as part of the simple archetype]

List<String> metaFilters = new ArrayList<String>();
metaFilters.add(System.getProperty("metaFilters", "-skip"));
configuredEmbedder().useMetaFilters(metaFilters);

2.   Avoid @Named annotation –

·      This makes jbehave interpret the name contained between the delimiters as the parameter name and look it up in the parameters provided by the Examples table. The default behaviour of parameter lookup is overridden via the ParameterControls.
·      This helps to avoid the use of @Named parameter annotation in the method definitions, and also avoids different aliases of steps
Add this line in the end of configuration() method –

.useParameterControls(new ParameterControls().useDelimiterNamedParameters(true)
    
                             
3.   Change the delimiters to [] –

·      This would define the delimiters to be used for parameter names. This will enable us to use [ ] instead of the default < >, in parameter names.
Add this line in the end of configuration() method -

.useNameDelimiterLeft("[").useNameDelimiterRight("]"));



MyStories.java:

public class MyStories extends JUnitStories {

private final static Logger log = Logger.getLogger(MyStories.class);

public MyStories() {

configuredEmbedder().embedderControls().doGenerateViewAfterStories(true).doIgnoreFailureInStories(true)

.doIgnoreFailureInView(true).useThreads(2).useStoryTimeoutInSecs(300);

// Custom Config >> Added to enable meta tag based filtering

List<String> metaFilters = new ArrayList<String>();

metaFilters.add(System.getProperty("metaFilters", "-skip"));

configuredEmbedder().useMetaFilters(metaFilters);

}

@Override

public Configuration configuration() {

log.info("setting JB configurations");

Class<? extends Embeddable> embeddableClass = this.getClass();

// Start from default ParameterConverters instance

ParameterConverters parameterConverters = new ParameterConverters();

// factory to allow parameter conversion and loading from external resources (used by StoryParser too)

ExamplesTableFactory examplesTableFactory = new ExamplesTableFactory(new LocalizedKeywords(),
new LoadFromClasspath(embeddableClass), parameterConverters);

// add custom converters

parameterConverters.addConverters(new DateConverter(new SimpleDateFormat("yyyy-MM-dd")),

new ExamplesTableConverter(examplesTableFactory));

return new MostUsefulConfiguration()

.useStoryLoader(new LoadFromClasspath(embeddableClass))

.useStoryParser(new RegexStoryParser(examplesTableFactory))

.useStoryReporterBuilder(new StoryReporterBuilder()

.withCodeLocation(CodeLocations.codeLocationFromClass(embeddableClass))

.withDefaultFormats()

.withFormats(CONSOLE, TXT, HTML, XML))

.useParameterConverters(parameterConverters)

// Custom Config >> This makes jbehave interpret the name contained between the delimiters as the
// parameter name and look it up in the parameters provided by the Examples table

.useParameterControls(new ParameterControls().useDelimiterNamedParameters(true)

// Custom Config >> This would define the delimiters to be used for parameter names. This will
// enable us to use [ ] instead of the default < >, in parameter names

.useNameDelimiterLeft("[").useNameDelimiterRight("]"));

}

@Override

public InjectableStepsFactory stepsFactory() {

return new InstanceStepsFactory(configuration(), new MySteps());

}

@Override

protected List<String> storyPaths() {

return new StoryFinder().findPaths(codeLocationFromClass(this.getClass()), "**/*.story", "**/excluded*.story");

}


}