Executing selenium tests in junit

To use Selenium with JUnit, you will have to add below dependencies.
 
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>2.53.0</version>
<scope>test</scope>
</dependency>

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

Then you can add below base test class. In this class, we have written before and after methods that are used to launch and close the webdriver.
 
package simple_selenium_tests;

import org.junit.After;
import org.junit.Before;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class BaseTest {

    public WebDriver driver;

    @Before
    public void setUp() {
        System.out.println("Launching browser");
        driver = new FirefoxDriver();
    }

    @After
    public void cleanup(){
        System.out.println("Closing the browser");
        driver.close();
        driver.quit();
    }
}

Then we can write actual tests as shown in below example. Note that below class extends the BaseTest class. So driver instance (inherited from BaseTest) can be used directly in the test.
 
package simple_selenium_tests;

import org.junit.Assert;
import org.junit.Test;
import seleniumtests.BaseTest;

public class SeleniumTest extends BaseTest {

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

}                    

Web development and Automation testing

solutions delivered!!