I have a production class which looks like
@Configurable
public class MyProductionClass {
@Resource private MyResource resource;
private String param;
public MyProductionClass(String param) {
this.param = param
}
public void aMethod() {
resource.doSomething();
//whatever, the previous line throws NullPointerException when testing
}
}
and a test class like
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/test-context.xml"})
@DirtiesContext(classMode = ClassMode.AFTER_CLASS)
@TestExecutionListeners(listeners = {DependencyInjectionTestExecutionListener.class})
public class MyProductionClassTest {
private MyProductionClass underTest;
@Test
public void aMethodTest() {
underTest = new MyProductionClass("aString");
underTest.aMethod();
}
}
I have some log and I can see Spring context being initialized correctly, with all beans described in test-context.xml
happily created, including resource
.
But, when the test runs underTest.aMethod()
a NullPointerException
is thrown saying resource is null
.
I use the same initialization (new MyProductionClass("aString")
) in production and there everything works flawlessly. Is there something I am missing when using @Configurable
classes with jUnit
?
Versions are:
- Spring
3.2.4
- jUnit
4.11
EDIT My understanding of @Configurable
: this issue may come from a misunderstanding of this feature. I understood it works so that I am not force to statically declare my @Configurable
class in any Spring context (either Java or XML based), but so that I can initialized the class with the new
operator and magically dependency are injected in the class. However, I do not know if this can work for tests (and I do not find any reason why it should not, a new
is a new
, whether it comes from a test class or from a production one)