【问题标题】:Spring Data neo4j JUnit4 setupSpring Data neo4j JUnit4 设置
【发布时间】:2015-06-04 16:47:25
【问题描述】:

我承认我完全是 Java 做事方式的新手,我完全迷失了试图让一个简单的单元测试运行。

我正在构建一个数据访问库并希望对其进行单元测试。我正在使用 Spring Data Neo4j 4.0.0.BUILD-SNAPSHOT 因为我需要连接到现实世界中的远程 Neo4j 服务器。

在整天与错误作斗争之后,我现在有了一个测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@ComponentScan(basePackages = {"org.mystuff.data"})
@ContextConfiguration(classes={Neo4jTestConfiguration.class})
public class PersonRepositoryTest {
    @Autowired
    PersonRepository personRepository;
    protected GraphDatabaseService graphDb;

    @Before
    public void setUp() throws Exception {
        graphDb = new TestGraphDatabaseFactory().newImpermanentDatabase();
    }

    @After
    public void tearDown() {
        graphDb.shutdown();
    }

    @Test
    public void testCreatePerson() throws Exception {
        assertNotNull(personRepository);
        Person p = new Person("Test", "User");
        personRepository.save(p);
    }
}

Neo4jTestConfiguration.java

@Configuration
@EnableNeo4jRepositories(basePackages = "org.mystuff.data")
@EnableTransactionManagement
public class Neo4jTestConfiguration extends Neo4jConfiguration {
    @Bean
    public SessionFactory getSessionFactory() {
        return new SessionFactory("org.mystuff.data");
    }

    @Bean
    public Neo4jServer neo4jServer() {
        // What to return here? I want in-memory database
        return null;
    }

    @Bean
    @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
    public Session getSession() throws Exception {
        return super.getSession();
    }
}

运行测试时,personRepository.save() 会抛出异常'No Scope registered for scope "session"' 我不知道我是否需要配置类,但如果没有它,我的测试类将无法工作,因为 Spring 需要 @ContextConfiguration 并且我想要 Spring 提供的所有 DI 优点(除其他外)。

如何让我的测试与 Spring 一起使用?

【问题讨论】:

    标签: intellij-idea gradle neo4j junit4 spring-data-neo4j-4


    【解决方案1】:

    您可以使用InProcessServer,它是一个内存数据库:

    @Bean
    public Neo4jServer neo4jServer() {
        return new InProcessServer();
    }
    

    省略会话范围,因为您的测试未在 Web 容器中运行。一个例子:https://github.com/neo4j-examples/sdn4-cineasts/blob/4.0-RC1/src/test/java/org/neo4j/cineasts/PersistenceContext.java

    这将需要此问题中描述的依赖项:Spring Data Neo4j 4.0.0.M1 Test Configuration

    在您的测试类PersonRepositoryTest 中,您无需构建数据库实例,您的测试将针对相同的InProcessServer 运行。 这是一个例子:https://github.com/neo4j-examples/sdn4-cineasts/blob/4.0-RC1/src/test/java/org/neo4j/cineasts/domain/DomainTest.java

    【讨论】:

    • 我似乎没有可用的 InProcessServer。这是哪里来的?
    • 找到了——我的 Gradle testCompile 定义中需要 spring-data-neo4j
    • 现在效果很好,谢谢。示例项目是一个很好的信息来源,真的很有帮助。
    • 欢迎。 github.com/neo4j-examples 中还有几个 sdn4* 示例
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多