Spring启动测试"没有可用的限定bean"

fen*_*e87 16 java spring spring-mvc cassandra

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

// 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();
  }
}
Run Code Online (Sandbox Code Playgroud)

所以基本上,我正在尝试引导一个spring应用程序,之后,做一些cassandra迁移.

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

// UserRepo.java
public interface UserRepo extends CassandraRepository<User> {
}
Run Code Online (Sandbox Code Playgroud)

现在我正在尝试使用以下简单测试用例来测试我的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()));
  }
}
Run Code Online (Sandbox Code Playgroud)

我希望测试通过,但相反,我得到一个错误说"没有合格的bean'类型'com.datastax.driver.core.Cluster'可用".看起来春天无法自动装配cluster物体,但为什么会这样呢?我该如何解决?非常感谢!

Jim*_*ins 28

测试环境需要知道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;
Run Code Online (Sandbox Code Playgroud)

  • 我希望集群实例能够像应用程序引导中那样自动连接。测试环境有什么区别? (3认同)
  • 吉姆的说法是正确的。在 Spring Boot 应用程序中,您有一个提供“Cluster”的配置类。您需要(并且应该有)一个单独的配置类或 XML 进行单元测试,以创建您需要的任何 bean。另外,“@Autowired private UserRepo userRepo = null;”是多余的。默认情况下这些都是空的。并且您应该尝试使用[构造函数注入](https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-spring-beans-and-dependency-injection.html)使测试更容易。 (2认同)
  • 从 1.4 开始,您是否正在使用 spring-boot-test 创建 spring-boot 应用程序,您可以使用 `@SpringBootTest` 注释您的测试类。 (2认同)