junit 测试中的@Autowired 和 UnsatisfiedDependencyException

@Autowired and UnsatisfiedDependencyException in a junit test

我正在编写一个 junit 测试,它必须从一些必须与 Cassandra 交互的自动装配的依赖项中调用一些方法,但我遇到了这个异常:

[ERROR] Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.21 s <<< FAILURE! - in unicon.mattheews.admin.service.repository.test.AdminUserRepositoryTests
[ERROR] testFindByUsername(unicon.mattheews.admin.service.repository.test.AdminUserRepositoryTests)  Time elapsed: 0.001 s  <<< ERROR!
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'unicon.mattheews.admin.service.repository.test.AdminUserRepositoryTests': Unsatisfied dependency expressed through field 'repository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'unicon.matthews.admin.service.repository.AdminUserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
 Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'unicon.matthews.admin.service.repository.AdminUserRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

这是junit测试:

import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.util.Version;
import org.springframework.test.context.junit4.SpringRunner;

import example.springdata.cassandra.util.CassandraKeyspace;
import unicon.matthews.admin.AdminUser;
import unicon.matthews.admin.service.repository.AdminUserRepository;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = CassandraConfiguration.class)
public class AdminUserRepositoryTests {

@ClassRule public final static CassandraKeyspace CASSANDRA_KEYSPACE = CassandraKeyspace.onLocalhost().atLeast(Version.parse("3.0"));

@Autowired AdminUserRepository repository;

@Before
public void setUp() throws Exception {
    repository.deleteAll();
}

@Test
public void testFindByUsername() {

    try {
        final String userName = "aironman";
        AdminUser.Builder myBuilderAdmin = AdminUser.Builder.class.newInstance();
        myBuilderAdmin.withId("id");
        myBuilderAdmin.withEmailAddress("some@domain.com");
        myBuilderAdmin.withOrgId("orgId");
        myBuilderAdmin.withPassword("some-password");
        myBuilderAdmin.withSuperAdmin(Boolean.TRUE);
        myBuilderAdmin.withTenantId("tenantId");
        myBuilderAdmin.withUserName(userName);
        //que viene aqui exactamente?
        Map<String, String> someMetadata = new HashMap<String, String>();
        someMetadata.put("some-key","some-value");
        myBuilderAdmin.withMetadata(someMetadata);
        AdminUser myAdminUser = myBuilderAdmin.build();
        repository.save(myAdminUser);
        Optional<AdminUser> loadedUserName = repository.findByUsername(userName);
        assertNotNull(loadedUserName);
        // assertThat(repository.findOne(homer.id).isPresent(), is(true));
        assertEquals("something went wrong!",userName,loadedUserName.get().getUsername());
    } catch (InstantiationException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }

    System.out.println("Done testFindByUsername!");
}

}

AdminUserRepository 看起来像:

import java.util.Optional;
import org.springframework.data.cassandra.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
import unicon.matthews.admin.AdminUser;


@Repository
public interface AdminUserRepository extends CrudRepository<AdminUser, String> {

@Query("select * from AdminUser where username = ?0")
Optional<AdminUser> findByUsername(final String userName);

}

Cassandra 配置看起来像:

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.cassandra.config.SchemaAction;
import org.springframework.data.cassandra.config.java.AbstractCassandraConfiguration;
import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories;

@Configuration
@EnableAutoConfiguration
class CassandraConfiguration {

@Configuration
@EnableCassandraRepositories
static class CassandraConfig extends AbstractCassandraConfiguration {

    @Override
    public String getKeyspaceName() {
        return "example";
    }

    @Override
    public SchemaAction getSchemaAction() {
        return SchemaAction.RECREATE;
    }
}

}

我了解到 spring 正在尝试实例化此 AdminUserRepository class,它是使用来自 spring-data 项目的 CrudRepository 创建的。假设如果我用 @Repository 标记这个接口,spring 将在 spring 上下文中实例化 class,以便另一个 bean 能够在其中自动装配它,所以,为什么 spring 无法实例化依赖项?

AdminUserRepository 接口位于 src/main/java 内,AdminUserRepositoryTests 位于 src/test/java.

这是我的真人pom.xml,请帮忙

用@Repository 标记Spring 数据存储库实际上没有任何作用。如果您不想启用 CrudRepository,则需要使用 @EnableJpaRepositories 注释您的配置。但是,由于您使用的是 Cassandra,我认为您更有可能希望使用 CassandraRepository ?

public interface AdminUserRepository extends CassandraRepository<AdminUser, String> {

@Query("select * from AdminUser where username = ?0")
Optional<AdminUser> findByUsername(final String userName);

}