The Selenium website seems to be biased towards TestNG. That’s fine but I’m using JUnit4.
One nice feature of the selenium testcase class is to produce a screendump for failures. But it’s a JUnit 3 class; it seems they have not noticed that JUnit4 exists.
So how to get a screendump with a JUnit4 test case? Wrapping and delegation works but I wanted to do it directly.
In JUnit4 you can install a Listener that is notified at test execution checkpoints. Since I care about only failures I defined it like this:
public class MyRunListener extends RunListener {
@Override
public void testFailure(Failure failure) throws Exception
{ }
}
To make JUnit4 use your listener you need to install it with a Runner. Here is a simple one that gets the job done.
public class MyRunner extends JUnit4ClassRunner {
private MyRunListener myRunListener;
public MyRunner(Class<?> c) throws InitializationError {
super(c);
myRunListener = new MyRunListener();
}
@Override
public void run(RunNotifier rn) {
rn.addListener(myRunListener);
super.run(rn);
}
}
Then in the superclass of my tests I use the RunWith annotation and specify my runner. Since I want to do the selenium setup only once per class I use the JUnit4 BeforeClass and AfterClass annotations. In production I’d probably start the server externally though. Or if I use Selenium userextensions.
@RunWith(MyRunner.class)
public class MyBaseTest {
protected static Selenium selenium;
private static SeleniumServer seleniumServer;
private static boolean startSeleniumServer = false;
@BeforeClass
public static void startUp() {
if (startSeleniumServer) {
try {
SeleniumServer.setReusingBrowserSessions(true);
seleniumServer = new SeleniumServer();
seleniumServer.start();
} catch (Exception e) {
e.printStackTrace();
}
}
selenium = new DefaultSelenium(serverHost, serverPort,
browserStartCommand, browserURL);
selenium.start();
selenium.setBrowserLogLevel(SeleniumLogLevels.INFO);
}
@AfterClass
public static void cleanUp() {
if (startSeleniumServer)
seleniumServer.stop();
selenium.stop();
}
etc.
Finally in my listeners testFailure method I get the Selenium instance from the base test class.
Selenium selenium = MyBaseTest.getSelenium();
It works!
In a future post, let’s see if I can use Spring for dependency injection of that selenium instance.
















Development notes by Gene De Lisa on topics relating to
Java and various open source projects such as
the Spring Framework, Hibernate and others.
Horaayy..there are 3 comment(s) for me so far ;)
[…] a previous post I wrote about using JUnit4 with […]
JUnit4 and Selenium…
[…]JUnit4 and Selenium[…]…
Hi
Take a look on Simplium that is a JUnit 4.5 framework for writing Selenium test cases.
http://simplium.sektor.se