首页 > 解决方案 > 如何让 ApplicationContext 识别来自 src/test/java 的 CouchBaseRepositoyr bean?

问题描述

我正在为使用 couchbase 存储库的反应式 Web 应用程序编写一些单元测试,但是ApplicationContext由于NoSuchBeanDefinitionException在尝试@Autowire使用ReactiveCouchbaseRepository.

从 src/main/java,应用程序运行得很好,我可以从 PostMan 发送请求并获得有效的响应。不需要配置类。我的 application.properties 设置如下:

spring.couchbase.bootstrap-hosts=subdomain.domain.com
spring.couchbase.bucket.name=some_bucket_name
spring.couchbase.bucket.password=a_password
spring.couchbase.env.timeouts.connect=10000

我创建了一个 src/test/resources 文件夹,将其标记为测试资源文件夹(在 IntelliJ 中),并复制到 application.properties,但仍然抛出相同的异常。我还在 test 文件夹中创建了一个 couchbase 配置类,如下所示:

@Configuration
@EnableCouchbaseRepositories
public class CouchbaseConfiguration extends AbstractCouchbaseConfiguration {


    @Value("${spring.couchbase.bootstrap-hosts}")
    private String hosts;

    @Value("${spring.couchbase.bucket.name}")
    private String bucketName;

    @Value("${spring.couchbase.bucket.password}")
    private String password;


    @Override
    protected List<String> getBootstrapHosts() {
        return Collections.singletonList(hosts);
    }

    @Override
    protected String getBucketName() {
        return bucketName;
    }

    @Override
    protected String getBucketPassword() {
        return password;
    }

}

我的测试类如下所示:

@RunWith(SpringRunner.class)
@WebFluxTest
public class ReactiveSpringApplicationTests {

    @Autowired
    WebTestClient webTestClient;

    @Test
    public void create_Test_Post_Event() throws Exception {

        EventData eventData = new EventData();
        eventData.setIdentifier("1111");

        webTestClient.post().uri("/ad/acc")
                .contentType(MediaType.APPLICATION_JSON_UTF8) // Set the media type of the body, as specified by the Content-Type header.
                .accept(MediaType.APPLICATION_JSON_UTF8) // Set the list of acceptable media types, as specified by the Accept header.
                .header("Corr", "0000")
                .body(Mono.just(eventData), EventData.class) // Set the body of the request to the given asynchronous Publisher.
                .exchange() // Perform the exchange without a request body.
                .expectStatus().isCreated()
                .expectHeader().contentType(MediaType.APPLICATION_JSON_UTF8)
                .expectBody(EventData.class);

    }
}

抛出以下异常(为简洁起见,省略了完整的异常堆栈,仅显示了第一个和最后一个异常):

java.lang.IllegalStateException: Failed to load ApplicationContext

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.amex.gar.accounts.repository.CouchBaseDocRepository<?, ?>' available: expected at least 1 bean which qualifies as autowire candidate.

CouchBaseDocRepository延伸ReactiveCouchBaseRepository

如何让 ApplicationContext 正确识别测试目录中的 couchbase 存储库?

标签: javaspringtestingcouchbasereactive

解决方案


推荐阅读