I am trying out to write an integration test for Spring Data Elastisearch repository in SpringBoot using Testcontainers and junit5. But the test fails with
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)}
How could I fix this issue? I tried googling but could not find anything appropriate.
DTO
@Data
@Document(indexName = "addresses")
public class Address {
String city;
String street;
GeoJsonPoint location;
}
Repository
@Repository
public interface AddressRepository extends ElasticsearchRepository<Address, String> {
}
The test 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);
}
}