Spring boot test "No qualifying bean of type available"

fengye87 picture fengye87 · Jul 5, 2017 · Viewed 38.7k times · Source

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

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

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

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!

Answer

JimHawkins picture JimHawkins · Jul 5, 2017

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

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;