Search code examples
javaspringdependency-injectionjunit4

Run unit tests against two different injected dependencies


I have two service beans in my application which both implement an interface. For that interface, all methods must perform the same (tho the internals differ).

So I'd like to write one set of tests that runs against both services. (Don't wanna write duplicate code)

What's the best way to structure my tests to accomplish this?

(I've tagged junit4, since that's the version to which I'm currently limited.)


Solution

  • The other answers here were all great, but didn't exactly fit my preferences. I ended up going with a combination of

    • JUnit's @RunWith(@Parameterized) (to run the tests for both services)
    • Spring's new Rules (to keep the @RunWith(SpringRunner.class) container, appcontext, webmvc and injection functionality)

    Here's the snippets:

    @RunWith(Parameterized.class)
    
    ...
    
    @Parameters(name = "Cached = {0}")
    public static Boolean[] data() {
        return new Boolean[] { Boolean.TRUE, Boolean.FALSE };
    }
    
    @ClassRule
    public static final SpringClassRule springClassRule = new SpringClassRule();
    
    @Rule
    public final SpringMethodRule springMethodRule = new SpringMethodRule();
    
    @Before
    public void setUp() {
         // logic to choose the injected service based on the true/false param
    }