用于@Configurable代码的jUnit的Spring上下文:Resource的NullPointerException

时间:2014-01-20 09:25:12

标签: java spring junit nullpointerexception junit4

我有一个类似于

的生产类
@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
  }
}

和像

这样的测试类
@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();
  }
}

我有一些日志,我可以看到Spring上下文正确初始化,test-context.xml中描述的所有bean都很乐意创建,包括resource

但是,当测试运行underTest.aMethod()时会抛出NullPointerException resource is null

我在制作中使用相同的初始化(new MyProductionClass("aString")),一切都完美无瑕。将@Configurable类与jUnit一起使用时,我是否缺少某些内容?

版本是:

  • 春天3.2.4
  • jUnit 4.11

编辑我对@Configurable的理解:此问题可能来自对此功能的误解。我知道它的工作原理使我无法在任何Spring上下文(基于Java或XML)中静态声明我的@Configurable类,但是我可以使用new运算符初始化类并且< em>神奇的依赖关系被注入到类中。但是,我不知道这是否可以用于测试(并且我没有找到任何理由为什么它不应该,newnew,无论它来自测试类还是来自生产一个)

1 个答案:

答案 0 :(得分:0)

你必须从弹簧容器中获取bean

@Autowired
private MyProductionClass underTest;
...
@Test
public void aMethodTest() {
underTest.aMethod();
}