Spring Boot测试“没有可用的类型限定豆”

56

我对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> {
}

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

// 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 对象,但是为什么呢?我该如何修复这个问题?万分感谢!


在您的代码中,当您看到一个类簇(实现接口Cluster)的bean时,它可以自动装配吗? - Jens
1
一个可能的解决方案是:删除这两行代码:@Autowired private Cluster cluster = null; - Jens
我没有定义任何 Cluster 类的 bean,它应该由 spring-boot-starter-data-cassandra 提供。如果我运行我的应用程序,它就可以工作。 - fengye87
测试配置中似乎缺少某些内容。 - Jens
1个回答

95

测试环境需要知道你的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;

3
我希望集群实例能像应用程序引导一样自动装配。测试环境有什么区别? - fengye87
1
据我所知,在执行测试时,调用SpringApplication.run(Application.class, args)的类Application不会被使用。 - JimHawkins
2
Jim的说法是正确的。在Spring Boot应用程序中,您有一个配置类提供了Cluster。您需要(并且应该有)一个单独的配置类或XML来创建任何所需的bean进行单元测试。此外,@Autowired private UserRepo userRepo = null;是多余的。它们默认为null。而且,您应该尝试使用构造函数注入使测试更容易。 - Christopher Schneider
3
如果您正在使用1.4及以上版本的spring-boot-test创建Spring Boot应用程序,则可以在测试类上注释@SpringBootTest - AndreFontaine
无法检索@EnableAutoConfiguration基础包。有任何想法吗? - kylie.zoltan
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接