2

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)

ThanksForAllTheFish
  • 7,101
  • 5
  • 35
  • 54

1 Answers1

0

you must get the bean from spring container

@Autowired
private MyProductionClass underTest;
...
@Test
public void aMethodTest() {
underTest.aMethod();
}
toby941
  • 378
  • 2
  • 4
  • You're right that the class under test _must_ come from the Spring container (strictly, from the context), but I'm not sure how that works with JUnit… – Donal Fellows Jan 20 '14 at 09:53
  • 1
    I am using `@Configurable`, so I think I do not need `MyProductionClass` to be declared in the Spring context and thus `Autowired`. See my edit to check my understanding of this Spring feature. – ThanksForAllTheFish Jan 20 '14 at 10:08
  • 2
    check your test-context.xml,[spring-autowiring-using-configurable](http://stackoverflow.com/questions/4703206/spring-autowiring-using-configurable),**@Configurable** use **AspectJ compiler**,i think load-time weaving is not enable in your test context – toby941 Jan 22 '14 at 02:23