Spring 在 SpringBoot 中使用 Testcontainers 进行数据 Elasticsearch 集成测试

Spring Data Elasticsearch integration test using Testcontainers in SpringBoot

我正在尝试使用 Testcontainers 和 junit5 在 SpringBoot 中为 Spring Data Elastisearch 存储库编写集成测试。但是测试失败

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.example.demo.AddressRepositoryTest': Unsatisfied dependency expressed through field 'repository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.demo.AddressRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

我该如何解决这个问题?我尝试使用谷歌搜索,但找不到合适的内容。

DTO

@Data
@Document(indexName = "addresses")
public class Address {
    String city;
    String street;
    GeoJsonPoint location;
}

存储库

@Repository
public interface AddressRepository extends ElasticsearchRepository<Address, String> {

}

测试AddressRepositoryTest.java

@ExtendWith(SpringExtension.class)
@Testcontainers
class AddressRepositoryTest {

    private static final String ELASTICSEARCH_VERSION = "7.10.1";

    static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
        @Override
        public void initialize(final ConfigurableApplicationContext configurableApplicationContext) {

        }
    }

    @Container
    public static ElasticsearchContainer container = new ElasticsearchContainer(DockerImageName
            .parse("docker.elastic.co/elasticsearch/elasticsearch-oss")
            .withTag(ELASTICSEARCH_VERSION));

    @Autowired
    AddressRepository repository;

    @Autowired
    private Config esConfig;

    @BeforeEach
    void setUp() {
        container.start();
        System.setProperty("elasticsearch.host", container.getContainerIpAddress());
        System.setProperty("elasticsearch.port", String.valueOf(container.getMappedPort(9300)));
        assertTrue(container.isRunning());
    }

    @AfterEach
    void tearDown() {
        container.stop();
    }

    @Test
    void save() {
        final Address address = new Address();
        address.setCity("Some city");
        address.setStreet("Some street");

        address.setLocation(GeoJsonPoint.of(0, 0));
        final Address save = repository.save(address);

    }
}

在 Spring 中你必须以某种方式初始化上下文,否则没有什么可以自动装配的。通常使用 @Import 注释来设置特定的配置,或者使用 @SpringBootTest 注释(在这种情况下,您不需要 @ExtendWith),如果这是一个测试。

请在 google 中搜索“spring 启动测试”或“spring 启动测试 jpa”。也许像 - https://www.baeldung.com/spring-boot-testing.

这是因为默认情况下没有创建上下文,所以没有什么可以自动装配的。 @ExtendWith(SpringExtension.class) 不创建上下文。在生产应用程序中,@SpringBootApplication 会这样做,对于测试,有一个 @SpringBootTest 替代方案。

我也建议看一本书,Spring在行动中,前两章可能就足够了。