繁体   English   中英

TestExecutionListeners注释可防止连接Spring bean

[英]TestExecutionListeners annotation prevents spring beans being wired in

带有spring例子cassandra-unit之后,我发现spring bean没有连接到testclass,导致nullpointer异常。 我试图最小化问题并发现它可能不是Cassandra部分,而是存在@TestExecutionListeners注释以及AbstractTestExecutionListener扩展类。

org.springframework:spring-core:4.2.0.RELEASE (Also fails with 3.2.14.RELEASE).
org.springframework:spring-test:4.2.0.RELEASE
junit.junit:4.11

JVM vendor/version: Java HotSpot(TM) 64-Bit Server VM/1.8.0_40
MAC OS X 10.10.5

我的TestClass看起来像:

@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({ AppTestListener.class }) <-- OK when removed
@ContextConfiguration(classes = { TestConfiguration.class })

public class MyTest {
  @Autowired
  private MyService myService;

  @Test
  public void testMyService() {
    Assert.assertNotNull(myService);
    Assert.assertEquals("didit", myService.doIt());
  }
}

AppTestListener:

public class AppTestListener extends AbstractTestExecutionListener {
  @Override
  public void beforeTestMethod(TestContext testContext) throws Exception {
    System.out.println("test");
  }
}

配置类没什么特别的(配置xml也失败了):

@Configuration
public class TestConfiguration {
  @Bean
  public MyService myService() {
    return new MyService(); 
  }
}

当我在MyTest中删除@TestExecutionListeners注释时,测试按预期完成,但是保留该注释会使assertNotNull上的unittest失败。 怎么了?

对于初学者来说,遗憾的是cassandra-unit示例并不是一个很好的例子,因为它会像你遇到的那样导致问题。

当我在MyTest中删除@TestExecutionListeners注释时,测试按预期完成,但是保留该注释会使assertNotNull上的unittest失败。 怎么了?

当您在不扩展使用@TestExecutionListeners注释的任何其他测试类的测试类上声明@TestExecutionListeners(AppTestListener.class)时,您实际上是在告诉Spring 加载AppTestListener ,而实际上您希望将AppTestListener与默认侦听器结合使用来自Spring(例如, DependencyInjectionTestExecutionListener ,它增加了对ApplicationContext中bean的依赖注入的支持)。

有关详细信息,请阅读Spring参考手册的整个TestExecutionListener配置部分。

以下是解决问题的方法。

在Spring Framework 4.1之前

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@TestExecutionListeners({
  CassandraUnitTestExecutionListener.class,
  DependencyInjectionTestExecutionListener.class,
  DirtiesContextTestExecutionListener.class,
  TransactionalTestExecutionListener.class
})
@CassandraUnit
public class MyCassandraUnitTest {

  @Test
  public void xxx_xxx() {
  }
}

在Spring Framework 4.1之后

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@TestExecutionListeners(
  listeners = CassandraUnitTestExecutionListener.class,
  mergeMode = MERGE_WITH_DEFAULTS
)
@CassandraUnit
public class MyCassandraUnitTest {

  @Test
  public void xxx_xxx() {
  }
}

问候,

Sam( Spring TestContext Framework的作者

ps我为Cassandra Unit创建了一个问题,以便他们在他们的例子中解决这个问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM