【问题标题】:Spring boot test "No qualifying bean of type available"春季启动测试“没有可用的合格bean”
【发布时间】:2017-12-09 01:39:20
【问题描述】:

我是 Spring boot 的新手,但这是我现在面临的问题:

// Application.java
public class Application {
  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }

  @Autowired
  private Cluster cluster = null;

  @PostConstruct
  private void migrateCassandra() {
    Database database = new Database(this.cluster, "foo");
    MigrationTask migration = new MigrationTask(database, new MigrationRepository());
    migration.migrate();
  }
}

所以基本上,我正在尝试引导一个 Spring 应用程序,然后进行一些 cassandra 迁移。

我还为我的用户模型定义了一个存储库:

// UserRepo.java
public interface UserRepo extends CassandraRepository<User> {
}

现在我正在尝试使用以下简单的测试用例来测试我的 repo 类:

// UserRepoTest.java
@RunWith(SpringRunner.class)
@AutoConfigureTestDatabase(replace = Replace.NONE)
@DataJpaTest
public class UserRepoTest {

  @Autowired
  private UserRepo userRepo = null;

  @Autowired
  private TestEntityManager entityManager = null;

  @Test
  public void findOne_whenUserExists_thenReturnUser() {
    String id = UUID.randomUUID().toString();
    User user = new User();
    user.setId(id);
    this.entityManager.persist(user);

    assertEquals(this.userRepo.findOne(user.getId()).getId(), id);
  }

  @Test
  public void findOne_whenUserNotExists_thenReturnNull() {
    assertNull(this.userRepo.findOne(UUID.randomUUID().toString()));
  }
}

我希望测试能够通过,但我收到一条错误消息,提示“没有可用的 'com.datastax.driver.core.Cluster' 类型的合格 bean”。看起来 spring 无法自动装配 cluster 对象,但这是为什么呢?我该如何解决?非常感谢!

【问题讨论】:

  • 在你的代码中哪里可以看到类集群的bean(接口集群的实现)??
  • 一种可能的解决方案:删除这两行:@Autowired private Cluster cluster = null;
  • 我没有定义Class Cluster的bean,应该是spring-boot-starter-data-cassandra提供的。如果我运行我的应用程序,它就可以工作。
  • 那么测试配置中缺少某些东西

标签: java spring spring-mvc cassandra


【解决方案1】:

测试环境需要知道你的bean是在哪里定义的,所以你必须告诉它位置。

在你的测试类中,添加@ContextConfiguration注解:

@RunWith(SpringRunner.class)
@AutoConfigureTestDatabase(replace = Replace.NONE)
@DataJpaTest
@ContextConfiguration(classes = {YourBeans.class, MoreOfYourBeans.class})
public class UserRepoTest {

  @Autowired
  private UserRepo userRepo = null;

  @Autowired
  private TestEntityManager entityManager = null;

【讨论】:

  • 我希望集群实例能够像在应用程序引导中那样自动连接。测试环境有什么区别?
  • AFAIK,执行测试时不使用您调用 SpringApplication.run(Application.class, args) 的类 Applcation
  • 吉姆的说法是正确的。在 Spring Boot 应用程序中,您有一个提供 Cluster 的配置类。您需要(并且应该拥有)一个单独的配置类或用于单元测试的 XML 来创建您需要的任何 bean。此外,@Autowired private UserRepo userRepo = null; 是多余的。这些默认为空。您应该尝试使用constructor injection 来简化测试。
  • 自 1.4 以来您是否正在使用 spring-boot-test 创建一个 spring-boot 应用程序,您可以使用 @SpringBootTest 注释您的测试类。
  • 不是@ContextConfiguration 我们不能提供basePackage吗?
猜你喜欢
  • 1970-01-01
  • 2016-12-13
  • 1970-01-01
  • 2017-09-25
  • 1970-01-01
  • 2021-08-31
  • 2018-01-21
  • 2016-03-03
  • 1970-01-01
相关资源
最近更新 更多