8

In the interest of DRY, I want to define my ContextConfiguration in a parent class and have all my test classes inherit it, like so:

Parent class:

package org.my;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "/org/my/Tests-context.xml")
public abstract class BaseTest {

}

Child class:

package org.my;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(inheritLocations = true)
public class ChildTest extends BaseTest {

    @Inject
    private Foo myFoo;

    @Test
    public void myTest() {
          ...
    }
}

According to the ContextConfiguration docs I should be able to inherit the parent's location, but I can't get it to work. Spring is still looking for a file in the default location (/org/my/ChildTest-context.xml) and barfs when it can't find it. I've tried the following with no luck:

  • Making the parent class concrete
  • Adding a no-op test to the parent class
  • adding an injected member to the parent class as well
  • combinations of the above

I'm on spring-test 3.0.7 and JUnit 4.8.2.

Evan Haas
  • 2,524
  • 2
  • 22
  • 34

1 Answers1

13

Remove the @ContextConfiguration(inheritLocations = true) on the child class. inheritLocations is set to true by default.

By adding the @ContextConfiguration(inheritLocations = true) annotation without specifying a locations ,you are telling to Spring to extended the list of resource locations by adding the default context which is /org/my/ChildTest-context.xml.

Try with something like this :

package org.my;

@RunWith(SpringJUnit4ClassRunner.class)
public class ChildTest extends BaseTest {

    @Inject
    private Foo myFoo;

    @Test
    public void myTest() {
          ...
    }
}
Jean-Philippe Bond
  • 10,089
  • 3
  • 34
  • 60
  • That was it! This reminds me, I need to go accept your other answer. You are officially the SO MVP for this week :-) – Evan Haas Jan 18 '13 at 17:52