I have basic Spring
repository:
@Repository
public interface LRepository extends MongoRepository<L, String> {}
And I am using it inside a service:
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SerImpl {
private final LRepository repository;
public String saveL(L l) {
l = repository.save(l);
return l.id;
}
}
On line with .save(l)
my test timeouts.
@SpringBootTest
@ExtendWith(SpringExtension.class)
@Testcontainers
@ContextConfiguration(initializers = {MongoIntegrationTest.TestPropertiesInitializer.class})
class MongoIntegrationTest {
private SerImpl serImpl;
@Autowired
private LRepository lRepository;
public static class TestPropertiesInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext configurableApplicationContext) {
final TestPropertyValues values = TestPropertyValues.of(
"spring.data.mongodb.host=localhost",
"spring.data.mongodb.username=root",
"spring.data.mongodb.password=example",
"spring.data.mongodb.authentication-database=admin",
"spring.data.mongodb.database=l",
"spring.data.mongodb.uri=mongodb://root:example@localhost:27017"
);
values.applyTo(configurableApplicationContext);
}
}
@Container
public GenericContainer mongoDb = new GenericContainer("mongo:4.2.2")
.withExposedPorts(27017)
.withEnv("MONGO_INITDB_ROOT_USERNAME", "root")
.withEnv("MONGO_INITDB_ROOT_PASSWORD", "example");
@BeforeEach
public void setUp() {
mongoDb.start();
String address = mongoDb.getContainerIpAddress();
//List<Integer> exposedPorts = mongoDb.getExposedPorts();
Integer port = mongoDb.getFirstMappedPort();
Map<String,String> map = mongoDb.getEnvMap();
serImpl = new SerImpl(lRepository);
}
@Test
public void testSimplePutAndGet() {
String id = serImpl.saveL(new L("aaa"));
assertNotNull(id);
}
}
On line l = repository.save(l);
I get an error saying
org.mongodb.driver.cluster : Cluster description not yet available. Waiting for 30000 ms before timing out.
I tried to fix it by increasing timeout:
@Configuration
public class MongoConfiguration {
@Bean
public MongoClientOptions mongoOptions() {
return MongoClientOptions
.builder()
.serverSelectionTimeout(180000)
.build();
}
}
But more time did not help me here.
L
is object with String
field.
I simplified code above to make it more MVCE.
When the test runs i see the container running and exposing the port.
If i start mongo container from docker the test is successful.
I am running it on Windows.