Automated Testing With JUnit And Selenium For Browser Compatibility

sadhvisingh1

sadhvisingh1

Posted on January 29, 2019

Automated Testing With JUnit And Selenium For Browser Compatibility

Cross browser testing as we know is a process where you test your website over multiple numbers of browser & browser versions running on different operating systems. This is done so to realize the cross browser compatibility of a website or a web app when accessed across a variety of browsers. If your web app isn’t cross browser compatible then not only would you be missing out on potential leads but your customer retention could also suffer. These browser differences could be anything from cross browser layout issues to cross browser compatible typography and these cross browser differences happen as each browser has a unique rendering engine, which is responsible for rendering web elements.

However, cross browser testing could be highly time-consuming if executed manually. Think about how many browser versions you would need to encounter from legacy to modern and the surplus variety of browsers available in the market. You also would have to consider specific browsers offered by specific mobile vending companies. There are ways you could fast track your manual cross browser testing effort and automation testing sits on top of the list for saving every day time and effort.

This article references automation testing with JUnit and Selenium for a web application through a simple script.

JUnit is an open source unit testing tool that helps to test units of code. It is mainly used for unit testing Java project, however, it can be used with Selenium Webdriver to automate testing of Web applications. So you can even perform automation testing of a web application with JUnit. To be precise JUnit is a unit testing framework for Java that helps to write test cases in a more structured and better format. Selenium and JUnit can be used independently of each other, though, testing with JUnit and Selenium combined helps to write test cases in a more structured way. We will be walking through the following sections for Selenium automation testing with JUnit framework for automating test script for web application testing over an online Selenium grid:

  • Downloading JUnit Jars.

  • Adding Jars to your Selenium project.

  • Incorporating JUnit annotations and method into your first selenium scripts.

  • Cloud testing with JUnit and Selenium Using LambdaTest.

Step 1. Downloading JUnit Jars

JUnit jar files can be downloaded from https://github.com/JUnit-team/JUnit4/wiki/Download-and-Install. The major jar files included are:

  • junit.jar

  • hamcrest-core.jar

Download and save these files in your system.

Step 2. Adding Jars To Your Selenium Project

In order to add your JUnit external jar files into your project, you need to have an advanced code editor/compiler tool of your preference. I usually work with eclipse so I would be narrating using the same. You also need to have Selenium jar files downloaded. In order to install eclipse, you can refer to its official website. Based on your operating system windows or OS, you can download accordingly. Post Eclipse setup you can download your Selenium jar files from its official website . In order to create your Selenium webdriver scripts, you need to use user language-specific drivers. In our case, we are using Java, though Selenium grid supports multiple languages like C#, Ruby, Python, Javascript along with Java. Download the Selenium jar files and include them into your code editor/compiler workspace, now for automating test script for testing with JUnit and Selenium grid, we need to include our downloaded JUnit Jar files. Follow the below steps to do so:

  • Right click on your created project and select properties:

  • Click on Java build path from the options:

  • Click on the ‘Add external Jars’ button and add your downloaded JUnit Jar files and click ‘OK’ post that:

This adds the JUnit jar files to your Selenium project. The major class file/source files that are commonly used in this JUnit Jar files are:

  • Assertions

  • Annotations

  • Parameterized

  • Ignore

  • TestListeners etc

For detail list on the class files or source files refer here. Now, let us incorporate JUnit into your Selenium project for proceeding web application testing with JUnit and Selenium.

This JUnit certification establishes testing standards for those who wish to advance their careers in Selenium automation testing with JUnit.

Here’s a short glimpse of the JUnit certification from LambdaTest:

Test your web and mobile apps on online Android Emulators . Ensure your apps are compatible across latest and legacy Android operating systems, devices, and browsers

Step 3. Incorporating JUnit To Your Selenium Script

The first block for building collaboration in this article, for testing with JUnit and Selenium for a web application would be to create our first JUnit Selenium simple script on https://www.lambdatest.com/.

Reference Code:

import static org.junit.Assert.*;
    import java.util.concurrent.TimeUnit;
    import org.junit.AfterClass;
    import org.junit.BeforeClass;
    import org.junit.Test;
    import org.openqa.selenium.By;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.chrome.ChromeDriver;



    public class Lamdatest_Junit {

        static WebDriver driver;

        [@BeforeClass](http://twitter.com/BeforeClass)
        public static void BrowserOpen()
        {
            System.setProperty("webdriver.chrome.driver", "path of your chromedriver"); 
            driver= new ChromeDriver() ;
            driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        }

        [@Test](http://twitter.com/Test)
        public void Register_User()
        {
            driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
            driver.get("[https://www.lambdatest.com/](https://www.lambdatest.com/) ");
            driver.manage().window().maximize();
            driver.findElement(By.xpath("//a[text()='Free Sign Up']")).click();
            driver.findElement(By.xpath("//input[[@name](http://twitter.com/name)='organization']")).sendKeys("LambdaTest");
            driver.findElement(By.xpath("//input[[@name](http://twitter.com/name)='first_name']")).sendKeys("Test");
            driver.findElement(By.xpath("//input[[@name](http://twitter.com/name)='last_name']")).sendKeys("User");
            driver.findElement(By.xpath("//input[[@name](http://twitter.com/name)='email']")).sendKeys("[User2@gmail.com](mailto:User2@gmail.com)");
            driver.findElement(By.xpath("//input[[@name](http://twitter.com/name)='password']")).sendKeys("TestUser123");
            driver.findElement(By.xpath("//input[[@name](http://twitter.com/name)='phone']")).sendKeys("9412262090");
            driver.findElement(By.xpath("//button[text()='SIGN UP']")).click();
            String url= driver.getCurrentUrl();
            assertEquals("fail- unable to register", url, "[https://accounts.lambdatest.com/user/email-verification](https://accounts.lambdatest.com/user/email-verification)");
        }


        [@AfterClass](http://twitter.com/AfterClass)
        public static void BrowserClose()
        {

            driver.quit();
        }


        }
Enter fullscreen mode Exit fullscreen mode

Details:

The above script opens the browser with https://www.lambdatest.com/ and clicks on ‘free sign up’ button to register. Post register, the script will check the URL it is redirected to in order to ensure a successful registration. We have used two classes of JUnit one is Annotations **class and the other **Assertions.

The script consists of three sections:

  • @BeforeClass — This annotation runs the piece of code before starting any annotation in the class. As you can see, here we have opened the chrome browser before performing any action on it. The main actions are performed in the @test annotation marked method.

  • @test — This test method carries the functionality where the application is opened and the registration process is carried out. To validate the result we have used assertion class where we are validating the success of the registration process using the context of current URL. This test annotation runs the piece of code after the @BeforeClass and @BeforeTest method and before the @AfterTest and @AfterClass method.

  • @AfterClass- This annotation tells JUnit to run the piece of code once all the test have been executed. This annotation method usually carries the process of closing the browser post all action items have been performed.

    Attaching video of the execution of the above script:

So far you have seen how to automate your web app testing with JUnit and Selenium using a local webdriver instance. However, there is a downside to that. You can only invoke the automated cross browser testing over the browsers that are installed in your machine. Plus, you need to have your machine every time that you aim for running automation testing with JUnit and Selenium for a web app. It is why testing on cloud is emerging as a dominant preference worldwide. LambdaTest is a cloud based cross browser testing tool that offers supports with Selenium grid, providing a solution to every obstacle you face while performing automation testing using your local machine. LambdaTest offers a Selenium grid consisting 2000+ browsers for you to perform automation testing effortlessly.

Let me demonstrate how you could easily perform automation testing using LambdaTest.

To run your test suite on our Selenium grid, you have to configure a couple of capabilities so that your tests execute on a remote browser. Refer to our Capability Generator Tool to help you fetch your desired capabilities at ease.

WebDriver driver = new RemoteWebDriver(new URL("https://" + username + ":" + accesskey + "@hub.lambdatest.com/wd/hub"),
    DesiredCapabilities.firefox());
Enter fullscreen mode Exit fullscreen mode

Now let’s start with a simple Selenium WebDriver test. Below is a JUnit Selenium script that will open a sample to-do application which will do following task:

  1. Mark first two items as mark done.

  2. Add a new item in the list.

  3. Return the added item.

        import org.junit.After;
        import org.junit.Before;
        import org.junit.Test;
        import org.junit.runner.RunWith;
        import org.openqa.selenium.JavascriptExecutor;
        import org.openqa.selenium.WebDriver;
        import org.openqa.selenium.remote.CapabilityType;
        import org.openqa.selenium.remote.DesiredCapabilities;
        import org.openqa.selenium.remote.RemoteWebDriver;
        import java.net.URL;
    
        public class JUnitTodo {
             public String username = "YOUR_USERNAME";
            public String authkey = "YOUR_ACCESS_KEY";
            public static RemoteWebDriver driver = null;
            public String gridURL = "[@hub](http://twitter.com/hub).lambdatest.com/wd/hub";
            boolean status = false;
    
            [@Before](http://twitter.com/Before)
            public void setUp() throws Exception {
               DesiredCapabilities capabilities = new DesiredCapabilities();
                capabilities.setCapability("browserName", "chrome");
                capabilities.setCapability("version", "70.0");
                capabilities.setCapability("platform", "win10"); // If this cap isn't specified, it will just get the any available one
                capabilities.setCapability("build", "LambdaTestSampleApp");
                capabilities.setCapability("name", "LambdaTestJavaSample");
                capabilities.setCapability("network", true); // To enable network logs
                capabilities.setCapability("visual", true); // To enable step by step screenshot
                capabilities.setCapability("video", true); // To enable video recording
                capabilities.setCapability("console", true); // To capture console logs
                try {
                    driver = new RemoteWebDriver(new URL("https://" + username + ":" + accesskey + gridURL), capabilities);
                } catch (MalformedURLException e) {
                    System.out.println("Invalid grid URL");
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            }
    
            [@Test](http://twitter.com/Test)
            public void testSimple() throws Exception {
               try {
                      //Change it to production page
                    driver.get("[https://4dvanceboy.github.io/lambdatest/lambdasampleapp.html](https://4dvanceboy.github.io/lambdatest/lambdasampleapp.html)");
    
                      //Let's mark done first two items in the list.
                      driver.findElement(By.name("li1")).click();
                    driver.findElement(By.name("li2")).click();
    
                     // Let's add an item in the list.
                      driver.findElement(By.id("sampletodotext")).sendKeys("Yey, Let's add it to list");
                    driver.findElement(By.id("addbutton")).click();
    
                      // Let's check that the item we added is added in the list.
                    String enteredText = driver.findElementByXPath("/html/body/div/div/div/ul/li[6]/span").getText();
                    if (enteredText.equals("Yey, Let's add it to list")) {
                        status = true;
                    }
                } catch (Exception e) {
                    System.out.println(e.getMessage());
                }
            }
    
            [@After](http://twitter.com/After)
            public void tearDown() throws Exception {
               if (driver != null) {
                    ((JavascriptExecutor) driver).executeScript("lambda-status=" + status); // relay whether the test has passed or failed as marked by the user
                    driver.quit();
                }
            }
        }
    

You could also test your local files through LambdaTest Selenium grid for performing automation testing of a web application with JUnit and Selenium. You can do with the help of advanced capabilities provided by LambdaTest Capabilities Generator. These advanced capabilities will help you to:

  • Perform test on your locally hosted web pages.

  • Generate browser console logs for every step executed through your test.

  • Configure a custom time zone for executing your test.

  • Generate network logs through your test execution.

If we want to activate all of the above-mentioned advanced capabilities then you need to add the below desired capabilities:

 DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability("tunnel",true); // allows you to run tests for your locally hosted web pages.
        capabilities.setCapability("console",true); // generates console logs
        capabilities.setCapability("network",true); // generates network logs
        capabilities.setCapability("timezone","UTC+12");  //considering you want your test to run on the time zone UTC+12.
Enter fullscreen mode Exit fullscreen mode

Test your web and mobile apps on online Emulators Android. Ensure your apps are compatible across latest and legacy Android operating systems, devices, and browsers

Parallel Testing

LambdaTest also provides the ability to perform parallel test execution. With LambdaTest parallel testing you could run a similar test across multiple browsers, simultaneously. This helps to bring down the time taken on test build activities, significantly. Here is an example of parallel testing performed to automate web application testing with JUnit and Selenium using LambdaTest.

To run a test on different browsers at the same time, you will need to create a helper class that extends paramerterized class (org.junit.runners.Parameterized) and implements RunnerScheduler class

(org.junit.runners.model.RunnerScheduler) to support JUnit tests in parallel. See the example below:

import java.util.concurrent.ExecutorService;
    import java.util.concurrent.Executors;
    import java.util.concurrent.TimeUnit;

    import org.junit.runners.Parameterized;
    import org.junit.runners.model.RunnerScheduler;

    public class Parallelized extends Parameterized {

        private static class ThreadPoolScheduler implements RunnerScheduler {
            private ExecutorService executor;

            public ThreadPoolScheduler() {
                String threads = System.getProperty("junit.parallel.threads", "15");
                int numThreads = Integer.parseInt(threads);
                executor = Executors.newFixedThreadPool(numThreads);
            }

            [@Override](http://twitter.com/Override)
            public void finished() {
                executor.shutdown();
                try {
                    executor.awaitTermination(10, TimeUnit.MINUTES);
                } catch (InterruptedException exc) {
                    throw new RuntimeException(exc);
                }
            }

            [@Override](http://twitter.com/Override)
            public void schedule(Runnable childStatement) {
                executor.submit(childStatement);
            }
        }

        public Parallelized(Class<?> klass) throws Throwable {
            super(klass);
            setScheduler(new ThreadPoolScheduler());
        }
    }
Enter fullscreen mode Exit fullscreen mode

Here is an example of JUnit Test, this would be representing the helper class used above for executing the parallel testing.

import org.openqa.selenium.By;
    import org.openqa.selenium.Platform;
    import org.openqa.selenium.WebDriver;
    import org.openqa.selenium.remote.DesiredCapabilities;
    import org.openqa.selenium.remote.RemoteWebDriver;
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.junit.runners.Parameterized;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.LinkedList;

    [@RunWith](http://twitter.com/RunWith)(Parallelized.class)
    public class JUnitConcurrentTodo {
         public String username = "YOUR_USERNAME";
        public String accesskey = "YOUR_ACCESS_KEY";
        public String gridURL = "[@hub](http://twitter.com/hub).lambdatest.com/wd/hub";

         public String platform;
         public String browserName;
         public String browserVersion;


        public RemoteWebDriver driver = null;

         boolean status = false;

            [@Parameterized](http://twitter.com/Parameterized).Parameters
         public static LinkedList<String[]> getEnvironments() throws Exception {
            LinkedList<String[]> env = new LinkedList<String[]>();
            env.add(new String[]{"WIN10", "chrome", "70.0"});
            env.add(new String[]{"macos 10.12","firefox","62.0"});
            env.add(new String[]{"WIN8","internet explorer","11"});
            return env;
        }


       public JUnitConcurrentTodo(String platform, String browserName, String browserVersion) {
            this.platform = platform;
            this.browserName = browserName;
            this.browserVersion = browserVersion;
         }

        [@Before](http://twitter.com/Before)
        public void setUp() throws Exception {
           DesiredCapabilities capabilities = new DesiredCapabilities();
            capabilities.setCapability("browserName", browser);
            capabilities.setCapability("version", browserVersion);
            capabilities.setCapability("platform", platform); // If this cap isn't specified, it will just get the any available one
            capabilities.setCapability("build", "JUnitParallelSample");
            capabilities.setCapability("name", "JUnitParallelSampleTest");
            capabilities.setCapability("network", true); // To enable network logs
            capabilities.setCapability("visual", true); // To enable step by step screenshot
            capabilities.setCapability("video", true); // To enable video recording
            capabilities.setCapability("console", true); // To capture console logs
            try {
                driver = new RemoteWebDriver(new URL("https://" + username + ":" + accesskey + gridURL), capabilities);
            } catch (MalformedURLException e) {
                System.out.println("Invalid grid URL");
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }

        [@Test](http://twitter.com/Test)
        public void testParallel() throws Exception {
           try {
                  //Change it to production page
                driver.get("[https://4dvanceboy.github.io/lambdatest/lambdasampleapp.html](https://4dvanceboy.github.io/lambdatest/lambdasampleapp.html)");

                  //Let's mark done first two items in the list.
                  driver.findElement(By.name("li1")).click();
                driver.findElement(By.name("li2")).click();

                 // Let's add an item in the list.
                  driver.findElement(By.id("sampletodotext")).sendKeys("Yey, Let's add it to list");
                driver.findElement(By.id("addbutton")).click();

                  // Let's check that the item we added is added in the list.
                String enteredText = driver.findElementByXPath("/html/body/div/div/div/ul/li[6]/span").getText();
                if (enteredText.equals("Yey, Let's add it to list")) {
                    status = true;
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }

        [@After](http://twitter.com/After)
        public void tearDown() throws Exception {
           if (driver != null) {
                ((JavascriptExecutor) driver).executeScript("lambda-status=" + status);
                driver.quit();
            }
        }
    }
Enter fullscreen mode Exit fullscreen mode

Check this out, How To Debug Websites Using Developer Tools for Safari

Web Application Testing With JUnit and Selenium On Cloud Is A Must

Cloud testing means testing cloud-based applications that are hosted on a cloud. Using Selenium along with JUnit to test cloud services for web apps becomes the most obvious choice due to its capabilities to run the script on multiple browsers and platforms with any language support one choose for. The reason makes the incorporation between JUnit and Selenium a lucrative choice for performing cross browser testing. With the use of JUnit, it provides a more structured way of writing your test that leads to better maintenance, quality and effectiveness as compared to without using any frameworks like JUnit. LambdaTest as a cross browser testing tool could help you significantly cut short on the time and effort you put in for executing automation testing with JUnit and Selenium. LambdaTest offers a Selenium grid consisting more than 2000+ browsers and also supports multiple programming languages such as Javascript, Python, Ruby, C# and PHP. Using Maven and Jenkins with Selenium and JUnit helps make a more powerful, smoother and end to end automation experience for cloud-based application, thereby providing for robustness to the whole flow. We will be demonstrating that in our upcoming articles, so stay tuned and happy testing!

💖 💪 🙅 🚩
sadhvisingh1
sadhvisingh1

Posted on January 29, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related