Select Page
Software Testing

Java: Useful Snippets for Automation Testers

Being a leading QA Company, we write blogs on all prominent software testing topics and tools using our real-world experience. So stay sharp by subscribing to our Newsletter.

Listen to this blog

We have a conviction that our day to day work should be a combination of hard and smart work. In automation testing, we can arrive at a solution for a problem in umpteen numbers of ways. However, at times a complex problem might have a simple solution. In this article, we are going to share Java snippets which are much useful for automation testers to do smart work.

Snippet #1-How to check a string contains only numeric value?We can check this criteria using Regex pattern or you can try with Long.parseLong method. However, we recommend you to use Apache Commons Lang3‘s NumberUtils to check whether a string has only numeric.

String str = "1234";
if(NumberUtils.isCreatable(str)){
System.out.println("True");
}
else{
System.out.println("False");
}} 
  

Snippet #2-How to get Apache POI Numeric Cell value as it appears in Spreadsheet? If you want to get the Numeric value from a cell as it appears in Excel, use the below snippet.

strCellValue=new DataFormatter().formatRawCellContents(cell.getNumericCellValue(),
                 cell.getCellStyle().getDataFormat(), cell.getCellStyle().getDataFormatString());
  

Snippet #3-How to set Network Conditions in Selenium? If you want to run your Selenium script in different network conditions, you can do it using Chrome CommandExecutor as shown below.

System.setProperty("webdriver.chrome.driver","drivers/chromedriver.exe");
ChromeDriver driver = new ChromeDriver();
CommandExecutor executor = driver.getCommandExecutor();

//Set the conditions
Map map = new HashMap();
map.put("offline", false);
map.put("latency", 5);
map.put("download_throughput", 5000);
map.put("upload_throughput", 5000);

Response response = executor.execute(new Command(driver.getSessionId(),"setNetworkConditions",
ImmutableMap.of("network_conditions", ImmutableMap.copyOf(map))));
driver.get("http://google.com");
  

Snippet #4-Filtering WebElements using Regular Expression

driver.get("file:///C:/sample.html");

List<WebElement> elements=driver.findElements( By.xpath("//input[@type='checkbox']"));

elements.stream()
     .filter(element->Pattern.compile("check_(\d+)_box").matcher(element.getAttribute("id")).matches())
     .forEach(element->element.click());  

Comments(0)

Submit a Comment

Your email address will not be published.

Talk to our Experts

    Amazing clients who trust us

    image
    image
    image
    image
    image
    image