Wednesday, February 10, 2010

Demo code to Start the Selenium RC server from code.

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.BindException;
import java.net.ServerSocket;
import org.openqa.selenium.server.RemoteControlConfiguration;
import org.openqa.selenium.server.SeleniumServer;
import org.testng.AssertJUnit;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.thoughtworks.selenium.DefaultSelenium;
import com.thoughtworks.selenium.Selenium;

public class RCDemo {

static int SELENIUM_PORT = 4444;
static SeleniumServer server ;
String URL= "http://selenium-tips.blogspot.com/";
String BROWSER = "*firefox";
Selenium selenium;

/**
* Starts the Selenium server using versioned firefox profile
*
* @throws IOException
*/
@BeforeMethod
public void setUp() throws Exception {
selenium = new DefaultSelenium("localhost", SELENIUM_PORT , BROWSER, URL);
selenium.start();
};

@BeforeClass
public static void startSeleniumServer() throws IOException {
try {
ServerSocket serverSocket = new ServerSocket(SELENIUM_PORT);
serverSocket.close();

// Server not up, start it
try {
RemoteControlConfiguration rcc = new RemoteControlConfiguration();
rcc.setTimeoutInSeconds(60);
rcc.setPort(SELENIUM_PORT);
PrintStream ps = System.out; // backup
String logfile = "result.log";
System.setOut(new PrintStream(new FileOutputStream(logfile)));
server = new SeleniumServer(false, rcc);
System.setOut(ps); // restore
} catch (Exception e) {
System.err.println("Could not create Selenium Server because of: "+ e.getMessage());
e.printStackTrace();
}
try {
server.start();
} catch (Exception e) {
System.err.println("Could not start Selenium Server because of: "+ e.getMessage());
e.printStackTrace();
}
} catch (BindException e) {
// assume Selenium Server already up
System.out.println("Selenium server already up, will reuse...");
}
}

@AfterClass
public void StopServer(){
server.stop();
}

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

@Test
public void testDemo() throws IOException, InterruptedException {
selenium.open("/");
AssertJUnit.assertEquals("Expected title not found.","Tips for Web Automation using Selenium", selenium.getTitle());
}
}