Saturday, 26 March 2016

Writing JUnit tests with Selenium Webdriver

JUnit framework is a popular unit testing framework in Testing world.

In this article, you will get to know how to write junit tests with selenium webdriver. All you need to write the JUnit tests is JUnit provider. Just add that dependency in your Java project and start writing the tests.

How to add JUnit dependency in your project?


Most of the maven and Gradle projects POM and build.gradle file is created with JUnit dependency automatically when you create such projects. But in case your POM.xml file does not have JUnit dependency, just add below lines in dependencies section your POM.xml

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
    <scope>test</scope>
</dependency>


If you are using Gradle based project, just add below line in build.gradle file. 

testCompile group: 'junit', name: 'junit', version: '4.11'

How to write JUnit tests for Selenium Webdriver?

We need to create a Class and methods in it annotated with @Test as shown in below example. You can execute this test by pressing CTRL+SHIFT+F10 in Intellij IDEA or you can just right click on the method and click on Run using JUnit.

public class FirefoxTests {

    static WebDriver driver;

    @Test    public void launchChrome() throws Exception{
        driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
        driver.manage().window().maximize();
        driver.get("http://www.softpost.org/selenium-test-page/");
        driver.close();
        driver.quit();
    }
}

Executing Selenium JUnit tests with Maven
You can also run JUnit tests using Maven Goals. Maven uses Surefire plug-in to run the tests during Test phase. You can also configure the Surefire plug-in to include or exclude the specific tests.
Just type below command in command prompt and all your tests will get executed.

mvn test

If you want to run specific tests, you can pass -Dtest parameter which runs tests in specific class. Say you want to run tests in only BookingTests class, then use below command.

mvn test -Dtest=BookingTests

Executing Selenium JUnit tests with Gradle
You can also run JUnit tests using Gradle tasks.
Just type below command in command prompt and all your tests will get executed.

gradle test

What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

No comments:

Post a Comment

Buy Best Selenium Books

Contributors