Running Selenium Tests with JUnit 4

Step 1: Create a new project Java SugarCRMJunitTests in Eclipse as shown in the below figure.

CreateNewJavaProject

Step 2: Right Click newly created Java Project (SugarCRMJunitTests) –> New –> Package –> Give name “SugarTests”

Step 3: Right Click SugarTests package –> New –> JUnit Test Case (Select checkboxes SetupBeforeClass, tearDownAfterClass)    –> Give the name as “SugarTestScripts”

createJunitTestCase

Step 4: Record “SugarCRM” Login test with Selenium IDE and export that to JUnit 4 format and copy the code into Eclipse JUnit Test Case.  Code should be as shown below:

package SugarTests;

import com.thoughtworks.selenium.*;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;

public class SugarTestScripts extends SeleneseTestCase{
    @BeforeClass
    public static void setUpBeforeClass() throws Exception {
        DefaultSelenium selenium = new DefaultSelenium(“localhost”, 4444, “*firefox”, “http://127.0.0.1/”);
        selenium.start();
    }

    @Test
    public void testSugarLogin() throws Exception {
        selenium.open(“http://127.0.0.1/sugarcrm/index.php?action=Login&module=Users”);
        selenium.type(“user_name”, “admin”);
        selenium.type(“user_password”, “admin123”);
        selenium.click(“login_button”);
        selenium.waitForPageToLoad(“30000”);
        verifyTrue(selenium.isTextPresent(“Home”));
        selenium.click(“link=Log Out”);
        selenium.waitForPageToLoad(“30000”);
    }
    @AfterClass
    public static void tearDownAfterClass() throws Exception {
        DefaultSelenium selenium = new DefaultSelenium(“localhost”, 4444, “*firefox”, “http://127.0.0.1/”);
        selenium.stop();
    }

}

Now try to run the JUnit Test Case:

  1. Run Selenium Server by double clicking the Selenium-server.bat file.  Selenium server should be running in the command prompt.
  2. Right click SugarTestScripts.java –> Run As –> JUnit Test
  3. This should open the browser and open the SugarCRM login screen and login.  Then logout.
  4. Browser should be closed

But execution does not generate any results since we have not either written any code to display the results or configured any other tool to generate report.

In the next post we will discuss about Ant and how it helps in generating nice HTML / XML reports

Comments 11

  • Hi,

    I have record a script through Selenium IDE :

    package example;

    import com.thoughtworks.selenium.*;
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;

    public class Newtest extends SeleneseTestCase {
    @Before
    public void setUp() throws Exception {
    selenium = new DefaultSelenium(“localhost”, 4444, “*chrome”, “http://www.google.com/”);
    selenium.start();
    }

    @Test
    public void newtest () throws Exception {
    selenium.open(“/webhp?hl=en”);
    selenium.type(“id=q”, “qwe”);
    selenium.click(“id=btnG”);
    selenium.waitForPageToLoad(“600000”);
    }

    @After
    public void tearDown() throws Exception {
    selenium.stop();
    }
    }

    which is running successfully through Selenium IDe but when i am excuting java code for same in Junit through Selenium RC +eclipse its giving error, please let me know where i am doing wrong.Thanks.

    • Hi Nithin,

      In the above code you need to make some changes:
      1. Change the package to respective package inside eclipse
      2. Replace the Newtest class with the Class you created

  • Hello, I am new in Selenium, and i have question, I`ve tried to run my testcase exported into JUnit from Selenium IDE 1.0.6 via IntelliJ IDEA, and i always have error CANNT FIND SYMBOL CLASS UTIL. Here is my code which i am trying to run.

    package testcase1;

    import com.thoughtworks.selenium.*;

    import testcase1.java.util.regex.Pattern;

    public class java {

    public class testcase1 extends SeleneseTestCase {
    public void setUp() throws Exception {
    setUp(“http://book.theautomatedtester.co.uk/chapter1/”, “*chrome”);
    }
    public void testTestcase1() throws Exception {
    selenium.open(“/”);
    selenium.click(“link=Chapter1”);
    selenium.waitForPageToLoad(“30000”);
    selenium.select(“selecttype”, “label=Selenium Core”);
    selenium.click(“verifybutton”);
    }
    }

    }

    Can you give me some help with this?

    • Please remove “import testcase1.java.util.regex.Pattern;” line and then execute. Reason is you are importing testcase1.java.util.regex.pattern means your testcase1 should have java classes (jdk library) in it that is absolutely wrong…

  • Hi Seetaram,

    Nice Post.
    I have some query on this post.
    I was return code,

    package sugarTests;

    import com.thoughtworks.selenium.*;
    import org.junit.After;
    import org.junit.Before;
    import org.junit.Test;
    import java.util.regex.Pattern;
    @SuppressWarnings({ “unused”, “deprecation” })
    public class SugarTestScripts extends SeleneseTestCase {
    @Before
    public void setUp() throws Exception {
    DefaultSelenium selenium = new DefaultSelenium(“localhost”, 4444, “*chrome”, “http://www.google.co.in/”);
    selenium.start();
    }

    @Test
    public void testUntitled() throws Exception {
    selenium.open(“/”);
    assertEquals(“Google”, selenium.getTitle());
    selenium.type(“id=lst-ib”, “selenium”);
    selenium.click(“name=btnG”);
    verifyTrue(selenium.isTextPresent(“Selenium – Web Browser Automation”));
    }

    @After
    public void tearDown() throws Exception {
    selenium.stop();
    }
    }

    I included Junit Jar, Selenium-java-2.15.0.jar, Selenium-java-2.15.0-srcs.jar
    If i did not include this jar that time i was getting errors on
    public class SugarTestScripts extends SeleneseTestCase
    And Selenium object on every line.

    Please do let me correct if i am wrong.

  • Hi All,

    Problem resolved i was getting com.google.charsets java class not found exception.
    But after add jar appengine-tools-sdk-1.2.1 it get resolved.

  • Thanks. This was very helpful 😉

  • I am getting java.lang.NullPointerException on this line
    selenium.open(“http://127.0.0.1/sugarcrm/index.php?action=Login&module=Users”);

  • hello,
    I am getting java.lang.NullPointerException on this line
    driver.findElement(By.linkText(“Home”)).click();

    package Regression;

    import java.util.regex.Pattern;
    import java.util.concurrent.TimeUnit;
    import org.junit.*;
    import static org.junit.Assert.*;
    import static org.hamcrest.CoreMatchers.*;
    import org.openqa.selenium.*;
    import org.openqa.selenium.chrome.ChromeDriver;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.support.ui.Select;

    public class cheers {
    private WebDriver driver;
    private String baseUrl;
    private boolean acceptNextAlert = true;
    private StringBuffer verificationErrors = new StringBuffer();

    @Before
    public void setUp() throws Exception {
    // driver = new FirefoxDriver();
    System.setProperty(“webdriver.gecko.driver”, “D:\\Selenium\\selenium3.0\\geckodriver-v0.10.0-win64\\geckodriver.exe”);
    WebDriver driver = new FirefoxDriver();
    baseUrl = “http://joincheers.com/ui/”;
    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
    }

    @Test
    public void testCheers() throws Exception {
    driver.get(baseUrl + “/ui/”);
    driver.findElement(By.linkText(“Home”)).click();
    driver.findElement(By.linkText(“Blog”)).click();
    driver.findElement(By.linkText(“FAQs”)).click();
    driver.findElement(By.linkText(“Gallery”)).click();
    driver.findElement(By.linkText(“Home”)).click();
    driver.findElement(By.linkText(“Contact”)).click();
    driver.findElement(By.linkText(“Home”)).click();
    }

    @After
    public void tearDown() throws Exception {
    driver.quit();
    String verificationErrorString = verificationErrors.toString();
    if (!””.equals(verificationErrorString)) {
    fail(verificationErrorString);
    }
    }

    private boolean isElementPresent(By by) {
    try {
    driver.findElement(by);
    return true;
    } catch (NoSuchElementException e) {
    return false;
    }
    }

    private boolean isAlertPresent() {
    try {
    driver.switchTo().alert();
    return true;
    } catch (NoAlertPresentException e) {
    return false;
    }
    }

    private String closeAlertAndGetItsText() {
    try {
    Alert alert = driver.switchTo().alert();
    String alertText = alert.getText();
    if (acceptNextAlert) {
    alert.accept();
    } else {
    alert.dismiss();
    }
    return alertText;
    } finally {
    acceptNextAlert = true;
    }
    }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.