JUnit4 and Selenium
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:
1 2 3 4 5 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
@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.
1 |
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.
Hi
Take a look on Simplium that is a JUnit 4.5 framework for writing Selenium test cases.
http://simplium.sektor.se