簡體   English   中英

Spring啟動測試“沒有可用的限定bean”

[英]Spring boot test “No qualifying bean of type available”

我是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();
  }
}

所以基本上,我正在嘗試引導一個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()));
  }
}

我希望測試通過,但相反,我得到一個錯誤,說“沒有合格的bean'類型'com.datastax.driver.core.Cluster'可用”。 看起來spring無法自動裝配cluster對象,但為什么會這樣呢? 我該如何解決? 非常感謝!

測試環境需要知道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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM