【问题标题】:Problem with connection to Neo4j test container using Spring boot 2 and JUnit5使用 Spring boot 2 和 JUnit5 连接到 Neo4j 测试容器的问题
【发布时间】:2019-12-10 09:01:30
【问题描述】:

使用 Spring boot 2 和 JUnit5 连接到 Neo4j 测试容器的问题 int 测试上下文。容器启动成功但是spring.data.neo4j.uri属性默认端口错误:7687,我猜这个URI在我调用neo4jContainer.getBoltUrl().的时候应该是一样的

在这种情况下一切正常:

@Testcontainers
public class ExampleTest {

    @Container
    private static Neo4jContainer neo4jContainer = new Neo4jContainer()
        .withAdminPassword(null); // Disable password

    @Test
    void testSomethingUsingBolt() {

        // Retrieve the Bolt URL from the container
        String boltUrl = neo4jContainer.getBoltUrl();
        try (
            Driver driver = GraphDatabase.driver(boltUrl, AuthTokens.none());
            Session session = driver.session()
        ) {
            long one = session.run("RETURN 1", 
             Collections.emptyMap()).next().get(0).asLong();
            assertThat(one, is(1L));
        } catch (Exception e) {
            fail(e.getMessage());
        }
    }
}

SessionFactory 不是按照这些建议使用自动配置为应用程序创建的 - https://www.testcontainers.org/modules/databases/neo4j/

当我尝试在测试上下文中创建自己的主 bean - SessionFactory 时,我收到这样的消息 - “在未加载容器之前无法返回 URI”

但应用程序使用自动配置和在容器中启动的 neo4j 可以完美运行和运行,测试上下文也无法告知

【问题讨论】:

    标签: spring spring-boot spring-data-neo4j junit5


    【解决方案1】:

    在这种情况下,您不能 100% 依赖 Spring Boot 的自动配置(用于生产),因为它将读取 application.properties 或使用连接的默认值。

    要实现您想要的,关键部分是创建一个自定义 (Neo4j-OGM) Configuration bean。 @DataNeo4jTest 注解由spring-boot-test-autoconfigure 模块提供。

    @Testcontainers
    @DataNeo4jTest
    public class TestClass {
      @TestConfiguration
      static class Config {
        @Bean
        public org.neo4j.ogm.config.Configuration configuration() {
              return new Configuration.Builder()
                  .uri(databaseServer.getBoltUrl())
                  .credentials("neo4j", databaseServer.getAdminPassword())
                  .build();
        }
      }
     // your tests
    }
    

    有关更广泛的解释,请查看blog post。特别是。 与 Neo4j-OGM 和 SDN 一起使用部分。

    【讨论】:

      猜你喜欢
      • 2021-02-08
      • 2020-02-06
      • 2020-12-04
      • 2019-09-16
      • 2020-09-19
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      • 2020-12-18
      相关资源
      最近更新 更多