JUnit4, Selenium and Spring test context

In a previous post I wrote about using JUnit4 with Selenium.

So how about injecting your JUnit run listener via Spring?

My first attempt modified my runner to be a subclass of SpringJUnit4ClassRunner

Then I created the usual XML spring config file but named it after my test class name. So for

FooTests I created FooTests-context.xml. If you want another name you can pass that into
@ContextConfiguration.

Here is a bit of it:

Here is is what I have for the test cases

and the JUnit 4 listener:

So there is the problem. Spring will autowire testcases but not the runners nor the listeners.

What is the Spring way? Forget the JUnit RunListener. You write a Spring TestExecutionListener.
But that’s not autowired either so you have to grab your beans yourself. Luckily you have access to
the Spring context.

and to make your listener get used you add it to the list of test execution listeners in your test classes.
I put it in the superclass of my test classes.

But you say, what about that new @Configurable annotation?
Can’t you use DI on an object that Spring does not instantiate?
Stay tuned.

3 thoughts on “JUnit4, Selenium and Spring test context”

  1. I’m interested in hearing more about your Spring/Selenium RC adventures. I’m getting ready to rewrite quite a few Selenium tests into using RC and taking the opportunity to create more manageable and reusable code. I’m a QA person by trade so I’m fuzzy on design pattern best practices, but I know from experience that good code makes life easier for everyone.

  2. Inspired by this post I made a class FooTests containing some dummy tests and a DummyTestExecutionListener that printed some stuff in the methods of the TestExecutionListener.

    Unfortunately I have to conclude that your TestExecutionListener alone will not cover exceptions in the constructor of the test class, neither in the @junit.org.Before (and I presume, neither in the @After)…

  3. Just as a comment,

    By convention, a Spring bean name should start lowercase: “selenium” instead of “Selenium”

    Cheers,

    Fran

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.