繁体   English   中英

在 Java 中测试配置类期间,Junit 无法检测到 @Autowired Bean

[英]Junit cannot detect an @Autowired Bean during a test of a configuration class in Java

我有一个像下面这样的配置类

@Configuration
public class Configuration {

  @Autowired
  private JdbcTemplate jdbcTemplate;

  @Bean
  SimpleJdbcCall simpleJdbcCall() {
    return new SimpleJdbcCall(jdbcTemplate).withProcedureName("");
  }

}

我正在尝试为此配置类编写单元测试。 我的测试类如下所示。

@ContextConfiguration(classes = { Configuration.class })
@RunWith(SpringRunner.class)
public class ConfigurationTest {

  ApplicationContextRunner context = new ApplicationContextRunner()
                                         .withUserConfiguration(Configuration.class);

  @Test
  public void should_check_presence_of_example_service() {
    context.run(it -> {
      assertThat(it).hasSingleBean(SimpleJdbcCall.class);
    });
  }
}

当我在ConfigurationTest类中运行测试时,出现如下错误。

创建名为“Configuration”的 bean 时出错:通过字段“jdbcTemplate”表达的不满足的依赖关系; 嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException:没有可用的“org.springframework.jdbc.core.JdbcTemplate”类型的合格 bean:预计至少有 1 个 bean 有资格作为自动装配候选。 依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}

我试图通过在 Configuration 类中创建一个 bean jdbcTemplate 并传递数据源来解决这个问题。 然后测试单元测试没有找到bean数据源。 之后,我在 ConfigurationTest 类中使用了 @TestConfiguration 并创建了一个模拟(jdbcTemplate)。 那也没有用。

我为我的问题找到了解决方案,我认为如果有人处于相同的情况,它可能对其他人有帮助。 实际上,我的目标是由于公司要求而增加测试覆盖率,以下解决方案对我有用。

我改变了我的配置类,如下所示

@Configuration
public class Configuration {

  @Bean
  SimpleJdbcCall simpleJdbcCall(DataSource dataSource) {
    return new SimpleJdbcCall(dataSource).withProcedureName("");
  }

} 

我不得不像下面一样改变我的测试类。 现在测试类没有抱怨了,我得到了 Configuration 类的 100% 覆盖率。

@SpringBootTest
public class ConfigurationTest {

  @TestConfiguration
  static class MyConfiguration {
    @Bean
    DataSource dataSource() {
      return mock(DataSource.class);
    }
  }

  @Autowired
  private DataSource dataSource;

  @Autowired
  private Configuration configuration;

  @Test
  public void should_check_presence_of_simpleJdbcCall_Bean() {
    SimpleJdbcCall simpleJdbcCall = configuration.simpleJdbcCall(dataSource);
    Assertions.assertNotNull(simpleJdbcCall);
  }

}

暂无
暂无

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

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