Spring boot 测试“没有可用类型的合格 bean" [英] Spring boot test "No qualifying bean of type available"

查看:73
本文介绍了Spring boot 测试“没有可用类型的合格 bean"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm quite a newbie to Spring boot, but here's the problem I'm facing now:

// 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 迁移.

So basically, I'm trying to bootstrap a spring application, and after that, do some cassandra migrations.

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

I also have defined a repository for my user model:

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

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

Now I'm trying to test my repo class using the following simple test case:

// 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 对象,但这是为什么呢?我该如何解决?非常感谢!

I would expect the test to pass, but instead, I got an error saying "No qualifying bean of type 'com.datastax.driver.core.Cluster' available". It looks like spring failed to autowire the cluster object, but why is that? How do I fix this? Thanks a lot!

推荐答案

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

The test environment needs to know where your beans are defined, so you have to tell it the location.

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

In your test class, add the @ContextConfiguration annotation:

@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;

这篇关于Spring boot 测试“没有可用类型的合格 bean"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆