0

Estoy realizando JUnit test para mongoDB con SpringBoot, es la primera vez que lo tengo que hacer, así que estoy copiando de un lado y de otro cosas de google que "creo" que son la solución, pero me está fallando la aplicación.

Lo que pretendo hacer son pruebas en una base de datos embebidas de mongoDB para los test, el problema es que no se puede crear la base de datos embebida.

Por un lado he agregado en el pom.xml:

<dependency>
    <groupId>de.flapdoodle.embed</groupId>
    <artifactId>de.flapdoodle.embed.mongo</artifactId>
    <version>1.50.2</version>
    <scope>runtime</scope>
</dependency>

He creado una clase Java:

@Configuration
@ComponentScan(excludeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = CommandLineRunner.class))
@EnableAutoConfiguration
public class TestApplicationConfiguration {

    @Bean 
    GenerarCsv service() {
        return new GenerarCsvImpl();
    }
}

Y la que implementará los test:

import org.junit.After;
import org.junit.Before;
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.test.context.ActiveProfiles;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.batch.DesarrolloBatch.model.Documento;
import com.batch.DesarrolloBatch.persistence.DocumentoRepository;
import com.batch.DesarrolloBatch.service.interfaces.GenerarCsv;
import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;

import de.flapdoodle.embed.mongo.MongodExecutable;
import de.flapdoodle.embed.mongo.MongodProcess;
import de.flapdoodle.embed.mongo.MongodStarter;
import de.flapdoodle.embed.mongo.config.IMongodConfig;
import de.flapdoodle.embed.mongo.config.MongodConfigBuilder;
import de.flapdoodle.embed.mongo.config.Net;
import de.flapdoodle.embed.mongo.distribution.Version;
import de.flapdoodle.embed.process.runtime.Network;


@RunWith(SpringJUnit4ClassRunner.class)
@ActiveProfiles("test")
@SpringBootTest(classes=TestApplicationConfiguration.class)
public class GenerarDocumentoTest {



    private static final String DATABASE_NAME = "documento";

    private MongodExecutable mongodExe;
    private MongodProcess mongod;
    private MongoClient mongo;

    @Before
    public void beforeEach() throws Exception {
        MongodStarter starter = MongodStarter.getDefaultInstance();
        String bindIp = "localhost";
        int port = 12345;
        IMongodConfig mongodConfig = new MongodConfigBuilder()
        .version(Version.Main.PRODUCTION)
        .net(new Net(bindIp, port, Network.localhostIsIPv6()))
        .build();
        this.mongodExe = starter.prepare(mongodConfig);
        this.mongod = mongodExe.start();
        this.mongo = new MongoClient(bindIp, port);
    }

    @After
    public void afterEach() throws Exception {
        if (this.mongod != null) {
            this.mongod.stop();
            this.mongodExe.stop();
        }
    }

    @Test
    public void shouldCreateNewObjectInEmbeddedMongoDb() {
        // given
        MongoDatabase db = mongo.getDatabase(DATABASE_NAME);
        db.createCollection("documento");
        MongoCollection<Documento> col = db.getCollection("documento", Documento.class);

        // when
        Documento doc = new Documento();
        doc.set_id("999999999999999999999999");
        col.insertOne(doc);

        // then
        assertEquals(1L, col.countDocuments());
    }

}

Lo que pretendo hacer es: Insertar 1 registro y luego comprobar que hay 1 registro.

Cuando ejecuto la aplicación obtengo el error de:

    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:117) ~[spring-test-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    ... 26 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'embeddedMongoServer' defined in class path resource [org/springframework/boot/autoconfigure/mongo/embedded/EmbeddedMongoAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [de.flapdoodle.embed.mongo.MongodExecutable]: Factory method 'embeddedMongoServer' threw exception; nested exception is de.flapdoodle.embed.process.exceptions.DistributionException: java.io.IOException: Could not open inputStream for http://downloads.mongodb.org/win32/mongodb-win32-x86_64-3.5.5.zip
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:627) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:607) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1321) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1160) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    ... 26 more
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [de.flapdoodle.embed.mongo.MongodExecutable]: Factory method 'embeddedMongoServer' threw exception; nested exception is de.flapdoodle.embed.process.exceptions.DistributionException: java.io.IOException: Could not open inputStream for http://downloads.mongodb.org/win32/mongodb-win32-x86_64-3.5.5.zip
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:622) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:607) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1321) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1160) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.6.RELEASE.jar:5.1.6.RELEASE]
Caused by: de.flapdoodle.embed.process.exceptions.DistributionException: java.io.IOException: Could not open inputStream for http://downloads.mongodb.org/win32/mongodb-win32-x86_64-3.5.5.zip
    at de.flapdoodle.embed.process.runtime.Starter.prepare(Starter.java:68) ~[de.flapdoodle.embed.process-1.50.1.jar:?]
    at org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration.embeddedMongoServer(EmbeddedMongoAutoConfiguration.java:116) ~[spring-boot-autoconfigure-2.1.4.RELEASE.jar:2.1.4.RELEASE]
    at org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration$$EnhancerBySpringCGLIB$$67c9dfd6.CGLIB$embeddedMongoServer$1(<generated>) ~[spring-boot-autoconfigure-2.1.4.RELEASE.jar:2.1.4.RELEASE]
    at org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration$$EnhancerBySpringCGLIB$$67c9dfd6$$FastClassBySpringCGLIB$$8d580d09.invoke(<generated>) ~[spring-boot-autoconfigure-2.1.4.RELEASE.jar:2.1.4.RELEASE]
    at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:363) ~[spring-context-5.1.6.RELEASE.jar:5.1.6.RELEASE]
    at org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration$$EnhancerBySpringCGLIB$$67c9dfd6.embeddedMongoServer(<generated>) ~[spring-boot-autoconfigure-2.1.4.RELEASE.jar:2.1.4.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:1.8.0_171]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_171]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[?:1.8.0_171]
    at java.lang.reflect.Method.invoke(Unknown Source) ~[?:1.8.0_171]
    ... 26 more
Caused by: java.io.IOException: Could not open inputStream for http://downloads.mongodb.org/win32/mongodb-win32-x86_64-3.5.5.zip
    at de.flapdoodle.embed.process.store.Downloader.downloadInputStream(Downloader.java:131) ~[de.flapdoodle.embed.process-1.50.1.jar:?]
    at de.flapdoodle.embed.process.store.Downloader.download(Downloader.java:69) ~[de.flapdoodle.embed.process-1.50.1.jar:?]
    at de.flapdoodle.embed.process.store.ArtifactStore.checkDistribution(ArtifactStore.java:66) ~[de.flapdoodle.embed.process-1.50.1.jar:?]
    at de.flapdoodle.embed.process.store.ExtractedArtifactStore.checkDistribution(ExtractedArtifactStore.java:60) ~[de.flapdoodle.embed.process-1.50.1.jar:?]
    at de.flapdoodle.embed.process.runtime.Starter.prepare(Starter.java:55) ~[de.flapdoodle.embed.process-1.50.1.jar:?]
Caused by: java.net.SocketTimeoutException: connect timed out
    at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method) ~[?:1.8.0_171]
    at java.net.DualStackPlainSocketImpl.socketConnect(Unknown Source) ~[?:1.8.0_171]
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source) ~[?:1.8.0_171]

En el error se puede ver una ruta http... , he probado a entrar y me descarga el archivo.zip, así que no sé porque no se lo puede descargar el SpringBoot. Además como dije, nunca he hecho esto antes, he ido haciendo un copy paste de lo que me he ido encontrando:

Por un lado busqué y añadí: - La dependencia del pom que tengo que usar para mongoDB embebido. - Como añadir un registro al mongoDB embebido.

Si alguien sabe cómo hacer todo este proceso más claro(y que funcione) porque solo leo broza en internet se lo agradecería. Un saludo.

EDITO:

He cambiado la dependencia del pom.xml

<dependency>
    <groupId>de.flapdoodle.embed</groupId>
    <artifactId>de.flapdoodle.embed.mongo</artifactId>
    <scope>test</scope>
</dependency>

Ahora no da error, pero se queda estancado en el 0%

019-06-12 09:45:02.242  INFO 14372 --- [           main] c.b.D.GenerarDocumentoTest               : The following profiles are active: test
2019-06-12 09:45:03.108  INFO 14372 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Bootstrapping Spring Data repositories in DEFAULT mode.
2019-06-12 09:45:03.282  INFO 14372 --- [           main] .s.d.r.c.RepositoryConfigurationDelegate : Finished Spring Data repository scanning in 166ms. Found 1 repository interfaces.
2019-06-12 09:45:04.005  INFO 14372 --- [           main] o.s.b.a.m.e.EmbeddedMongo                : Download Version{3.5.5}:Windows:B64 : starting...
2019-06-12 09:45:06.621  INFO 14372 --- [           main] o.s.b.a.m.e.EmbeddedMongo                : Download Version{3.5.5}:Windows:B64 : DownloadSize: 245893992
2019-06-12 09:45:08.809  INFO 14372 --- [           main] o.s.b.a.m.e.EmbeddedMongo                : Download Version{3.5.5}:Windows:B64 : 0 %
5
  • 1
    el puerto por defecto de mongodb no es el 27017 ?? tienes un 12345 el 11 jun. 2019 a las 16:15
  • Ya lo he cambiado, sigue saliendo el mismo error.
    – EduBw
    el 12 jun. 2019 a las 6:16
  • @JackNavaRow edité el post, se queda estancado en el 0%..
    – EduBw
    el 12 jun. 2019 a las 7:50
  • abre un terminal e intenta hacer mongo el 12 jun. 2019 a las 13:11
  • Tengo mi mongo de prueba que lo he usado estos días
    – EduBw
    el 12 jun. 2019 a las 13:13

0

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

Examina otras preguntas con la etiqueta o formula tu propia pregunta.