是否有使用 JUnit 5 扩展模型的 Neo4j 测试工具?

Is there a Neo4j test harness that uses the JUnit 5 Extension Model?

在为 Neo4j 编写测试用例时,我想继续使用 JUnit 5 扩展模型,而不是使用 org.junit.vintagejunit-jupiter-migrationsupport。目前我只能找到 JUnit 4 的 Neo4j 测试工具,它使用 TestRule 并且依赖于 org.junit.vintagejunit-jupiter-migrationsupport

是否有使用扩展模型的 JUnit 5 的 Neo4j 测试工具?

参考文献:
Neo4j:Home, GitHub
Neo4j test-harness: Maven, GitHub, pom.xml
JUnit 4:GitHub
JUnit 4 TestRule: JUnit 4 Guide, JUnit 4.12 API, Neo4jRule GitHub
JUnit 5:GitHub
JUnit 5 Extension ModelJUnit 5 User Guide, GitHub
JUnit 5 org.junit.vintageJUnit 5 User Guide, Test-harness pom.xml
JUnit 5 junit-jupiter-migrationsupportJUnit 5 User Guide, Test-harness pom.xml


我知道可以在混合环境中使用 JUnit 4 和 JUnit 5,例如Mixing JUnit 4 and JUnit 5 tests.

我已经开始在 A Guide to JUnit 5 Extensions 的帮助下编写我自己的 Neo4j JUnit 5 扩展,但是如果带有 JUnit 5 扩展模型的标准 Neo4j 测试工具已经存在,为什么要创建我自己的。

可能是我只是用错误的关键字进行查询,这些关键字只是 neo4jJUnit 5 但相同的结果不断出现,none 这导致了我寻求.

检查了 JUnit Jupiter Extensions 并发现 none 适用于 Neo4j。

编辑

概念验证

由于下面的代码只是概念证明,因此未作为公认答案发布,但希望在几天内发布。

事实证明,将 JUnit 5 Jupiter 扩展添加到现有的 JUnit TestRlue 并不是那么糟糕。一路上有一些艰难的地方,如果你像我一样并且没有生活和呼吸一种单一的编程语言或一套工具,你必须花一些时间来理解它的精神;如果你问我,那应该是一个 SO 标签。

注意:此代码是 Neo4j TestRuleA Guide to JUnit 5 Extensions

中的一些代码的组合

从 Neo4j 开始 TestRule 只需更改工具:
删除 TestRule
添加 BeforeEachCallbackAfterEachCallback

注意:在 Neo4j 中使用 BeforeEachAfterEach 而不是 BeforeAllAfterAll,因为在创建节点时的每个新测试中,如果创建了新节点与之前的测试相同并且数据库不是新数据库然后检查节点的 id 将不同,因为为每个测试创建一个新节点并获得不同的 id。因此,为避免此问题并以与使用 Neo4j TestRule 相同的方式进行操作,为每个测试实例创建一个新数据库。我确实研究过在测试之间重置数据库,但似乎唯一的方法是删除构成数据库的所有文件。 :(

/*
 * Copyright (c) 2002-2018 "Neo4j,"
 * Neo4j Sweden AB [http://neo4j.com]
 *
 * This file is part of Neo4j.
 *
 * Neo4j is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
//package org.neo4j.harness.junit;
package org.egt.neo4j.harness.example_002.junit;

// References:
// GitHub - junit-team - junit5 - junit5/junit-jupiter-engine/src/test/java/org/junit/jupiter/engine - https://github.com/junit-team/junit5/tree/releases/5.3.x/junit-jupiter-engine/src/test/java/org/junit/jupiter/engine/extension

// Notes:
// With JUnit 4 TestRule there was basically one rule that was called at multiple points and for multiple needs.
// With JUnit 5 Extensions the calls are specific to a lifecycle step, e.g. BeforeAll, AfterEach,
// or specific to a need, e.g. Exception handling, maintaining state across test,
// so in JUnit 4 where a single TestRule could be created in JUnit5 many Extensions need to be created.
// Another major change is that with JUnit 4 a rule would wrap around a test which would make
// implementing a try/catch easy, with JUnit 5 the process is broken down into a before and after callbacks
// that make this harder, however because the extensions can be combined for any test,
// adding the ability to handle exceptions does not require adding the code to every extension,
// but merely adding the extension to the test. (Verify this).

import java.io.File;
import java.io.PrintStream;
import java.util.function.Function;

import org.junit.jupiter.api.extension.*;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.config.Setting;

import org.egt.neo4j.harness.example_002.ServerControls;
import org.egt.neo4j.harness.example_002.TestServerBuilder;
import org.egt.neo4j.harness.example_002.TestServerBuilders;

/**
 * A convenience wrapper around {@link org.neo4j.harness.TestServerBuilder}, exposing it as a JUnit
 * {@link org.junit.Rule rule}.
 *
 * Note that it will try to start the web server on the standard 7474 port, but if that is not available
 * (typically because you already have an instance of Neo4j running) it will try other ports. Therefore it is necessary
 * for the test code to use {@link #httpURI()} and then {@link java.net.URI#resolve(String)} to create the URIs to be invoked.
 */
//public class Neo4jRule implements TestRule, TestServerBuilder
public class Neo4jDatabaseSetupExtension implements  BeforeEachCallback, AfterEachCallback, TestServerBuilder
{
    private TestServerBuilder builder;
    private ServerControls controls;
    private PrintStream dumpLogsOnFailureTarget;

    Neo4jDatabaseSetupExtension(TestServerBuilder builder )
    {
        this.builder = builder;
    }

    public Neo4jDatabaseSetupExtension( )
    {
        this( TestServerBuilders.newInProcessBuilder() );
    }

    public Neo4jDatabaseSetupExtension(File workingDirectory )
    {
        this( TestServerBuilders.newInProcessBuilder( workingDirectory ) );
    }

    @Override
    public void afterEach(ExtensionContext context) throws Exception {

        if (controls != null)
        {
            controls.close();
        }
    }

    @Override
    public void beforeEach(ExtensionContext context) throws Exception {
        controls = builder.newServer();
    }

    @Override
    public ServerControls newServer() {
        throw new UnsupportedOperationException( "The server cannot be manually started via this class, it must be used as a JUnit 5 Extension." );
    }

    @Override
    public TestServerBuilder withConfig(Setting<?> key, String value) {
        builder = builder.withConfig( key, value );
        return this;
    }

    @Override
    public TestServerBuilder withConfig(String key, String value) {
        builder = builder.withConfig( key, value );
        return this;
    }

    @Override
    public TestServerBuilder withExtension(String mountPath, Class<?> extension) {
        builder = builder.withExtension( mountPath, extension );
        return this;
    }

    @Override
    public TestServerBuilder withExtension(String mountPath, String packageName) {
        builder = builder.withExtension( mountPath, packageName );
        return this;
    }

    @Override
    public TestServerBuilder withFixture(File cypherFileOrDirectory) {
        builder = builder.withFixture( cypherFileOrDirectory );
        return this;
    }

    @Override
    public TestServerBuilder withFixture(String fixtureStatement) {
        builder = builder.withFixture( fixtureStatement );
        return this;
    }

    @Override
    public TestServerBuilder withFixture(Function<GraphDatabaseService, Void> fixtureFunction) {
        builder = builder.withFixture( fixtureFunction );
        return this;
    }

    @Override
    public TestServerBuilder copyFrom(File sourceDirectory) {
        builder = builder.copyFrom( sourceDirectory );
        return this;
    }

    @Override
    public TestServerBuilder withProcedure(Class<?> procedureClass) {
        builder = builder.withProcedure( procedureClass );
        return this;
    }

    @Override
    public TestServerBuilder withFunction(Class<?> functionClass) {
        builder = builder.withFunction( functionClass );
        return this;
    }

    @Override
    public TestServerBuilder withAggregationFunction(Class<?> functionClass) {
        builder = builder.withAggregationFunction( functionClass );
        return this;
    }
}

接下来,为了让每个测试实例都有一个新的 GraphDatabaseService,它是用 ServerControls 创建的,实施 JUnit 5 ParameterResolver。

package org.egt.neo4j.harness.example_002.junit;

import org.egt.neo4j.harness.example_002.ServerControls;
import org.egt.neo4j.harness.example_002.TestServerBuilders;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;

public class Neo4jDatabaseParameterResolver implements ParameterResolver {

    @Override
    public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {
        boolean result = parameterContext.getParameter()
                .getType()
                .equals(ServerControls.class);

        return result;
    }

    @Override
    public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) throws ParameterResolutionException {

        Object result = (ServerControls)TestServerBuilders.newInProcessBuilder().newServer();

        return result;
    }
}

最后剩下的就是将 Neo4j JUnit 5 扩展模型与 @ExtendWith@Test 一起使用:

package org.egt.example_002;

import org.egt.neo4j.harness.example_002.ServerControls;
import org.egt.neo4j.harness.example_002.junit.Neo4jDatabaseParameterResolver;
import org.egt.neo4j.harness.example_002.junit.Neo4jDatabaseSetupExtension;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;

import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Node;
import org.neo4j.graphdb.Transaction;

import static org.junit.jupiter.api.Assertions.assertEquals;

@ExtendWith({ Neo4jDatabaseSetupExtension.class, Neo4jDatabaseParameterResolver.class })
public class Neo4jUnitTests {

    private ServerControls sc;
    private GraphDatabaseService graphDb;

    public Neo4jUnitTests(ServerControls sc) {
        this.sc = sc;
        this.graphDb = sc.graph();
    }

    @Test
    public void shouldCreateNode()
    {
        // START SNIPPET: unitTest
        Node n;
        try ( Transaction tx = graphDb.beginTx() )
        {
            n = graphDb.createNode();
            n.setProperty( "name", "Nancy" );
            tx.success();
        }

        long id = n.getId();
        // The node should have a valid id
        assertEquals(0L, n.getId());

        // Retrieve a node by using the id of the created node. The id's and
        // property should match.
        try ( Transaction tx = graphDb.beginTx() )
        {
            Node foundNode = graphDb.getNodeById( n.getId() );
            assertEquals( foundNode.getId(),  n.getId() );
            assertEquals( "Nancy" , (String)foundNode.getProperty("name") );
        }
        // END SNIPPET: unitTest

    }
}

我在这样做的过程中学到的一个重要的事情是 TestRule 代码似乎是 do everything in one class 而新的扩展模型使用许多扩展来做同样的事情。因此,Neo4j TestRule 的日志记录、异常处理和其他内容不在此概念证明中。然而,因为扩展模型允许您混合和匹配扩展,添加日志记录和异常处理就像使用来自另一个地方的扩展一样简单,只需添加 @ExtendWith 这就是为什么我没有为此创建它们概念证明。

你也会注意到我更改了包名,我这样做只是为了避免与同一项目中以独立方式实现代码其他部分的其他代码发生冲突,这样我就可以走到这个有效的概念证明。

最后,如果 JUnit 4 Neo4j TestRule class 和 JUnit 5 扩展模型 class 都可以从基础 class 继承然后可用,我不会感到惊讶在同一个测试框架中; fingers crossed。显然,大多数基础 class 将从 Neo4j TestRule class.

中提取

不是真正的答案,但我有一个 Neo4jExtension class,它是一个 JUnit 5 扩展。
我的大部分是硬编码的,因为我想要一些对我来说可以快速工作的东西。
它使用螺栓连接器创建一个嵌入式 Neo4j 数据库。
它还加载一些 apoc 过程和函数并加载初始数据以进行测试。
你的方法比较有趣。

import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.webresources.TomcatURLStreamHandlerFactory;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolutionException;
import org.junit.jupiter.api.extension.ParameterResolver;
import org.neo4j.graphdb.GraphDatabaseService;
import org.neo4j.graphdb.Transaction;
import org.neo4j.graphdb.factory.GraphDatabaseFactory;
import org.neo4j.graphdb.factory.GraphDatabaseSettings;
import org.neo4j.internal.kernel.api.exceptions.KernelException;
import org.neo4j.kernel.configuration.BoltConnector;
import org.neo4j.kernel.configuration.Settings;
import org.neo4j.kernel.impl.proc.Procedures;
import org.neo4j.kernel.internal.GraphDatabaseAPI;

import java.io.File;
import java.util.List;

import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Arrays.asList;
import static org.neo4j.helpers.ListenSocketAddress.listenAddress;
import static org.neo4j.kernel.configuration.BoltConnector.EncryptionLevel.DISABLED;
import static org.neo4j.kernel.configuration.Connector.ConnectorType.BOLT;
import static org.neo4j.kernel.configuration.Settings.FALSE;
import static org.neo4j.kernel.configuration.Settings.STRING;
import static org.neo4j.kernel.configuration.Settings.TRUE;

@Slf4j
public class Neo4jExtension implements
        BeforeAllCallback, AfterAllCallback, ParameterResolver,
        BeforeEachCallback, AfterEachCallback {

    private static final File DB_PATH = new File("target/neo4j-test");

    private GraphDatabaseService graphDb;
    private Transaction currentTransaction;

    @Override
    public void beforeAll(ExtensionContext extensionContext) throws Exception {
        FileUtils.deleteDirectory(DB_PATH);
        TomcatURLStreamHandlerFactory.disable();
        final BoltConnector boltConnector = new BoltConnector("bolt");
        graphDb = new GraphDatabaseFactory()
                .newEmbeddedDatabaseBuilder(DB_PATH)
                .setConfig(Settings.setting("dbms.directories.import", STRING, "data"),"../../data")
                .setConfig(Settings.setting("dbms.security.procedures.unrestricted", STRING, "apoc.*"),"apoc.*")
                .setConfig(boltConnector.type, BOLT.name())
                .setConfig(boltConnector.enabled, TRUE)
                .setConfig(boltConnector.listen_address, listenAddress("127.0.0.1", 7676))
                .setConfig(boltConnector.encryption_level, DISABLED.name())
                .setConfig(GraphDatabaseSettings.auth_enabled, FALSE)
                .newGraphDatabase();
        Procedures procedures = ((GraphDatabaseAPI) graphDb).getDependencyResolver().resolveDependency(Procedures.class);
        List<Class<?>> apocProcedures = asList(apoc.convert.Json.class);
        apocProcedures.forEach((procedure) -> {
            try {
                procedures.registerFunction(procedure);
                procedures.registerProcedure(procedure);
            } catch (KernelException e) {
                e.printStackTrace();
            }
        });
        final String importScript = FileUtils.readFileToString(new File("data/import_data.cql"), UTF_8);
        final String[] split = importScript.split(";");
        for (String query : split) {
            if (StringUtils.isNotBlank(query)) {
                graphDb.execute(query);
            }
        }
    }

    @Override
    public void afterAll(ExtensionContext extensionContext) throws Exception {
        graphDb.shutdown();
    }

    @Override
    public void beforeEach(ExtensionContext extensionContext) throws Exception {
        currentTransaction = graphDb.beginTx();
    }

    @Override
    public void afterEach(ExtensionContext extensionContext) throws Exception {
        currentTransaction.failure();
        currentTransaction.close();
    }

    @Override
    public boolean supportsParameter(ParameterContext parameterContext,
                                     ExtensionContext extensionContext) throws ParameterResolutionException {
        return parameterContext.getParameter().getType().equals(GraphDatabaseService.class);
    }

    @Override
    public Object resolveParameter(ParameterContext parameterContext,
                                   ExtensionContext extensionContext) throws ParameterResolutionException {
        return graphDb;
    }
}

更新: 接近 Neo4J/Spring 数据生态系统的人建议不要使用 Neo4jExtention。有关详细信息,请参阅 this answer


现在(自 2019 年 1 月起)Neo4jExtension for JUnit 5 基本上完成了 Neo4jRule 为 Junit 4 所做的工作。

你这样使用它:

@ExtendWith(org.neo4j.harness.junit.extension.Neo4jExtension.class)
class MyTest {
    ...

如果您使用的是 Spring / Spring Data Neo4j,您可能会发现此扩展在 SpringExtension 上的表现不是特别好。我在这里的另一个问答中描述了如何解决这个问题: How do I set up a Spring Data Neo4j integration test with JUnit 5 (in Kotlin)?

最简单的方法可能是根本不使用扩展程序。

对 Neo4j 使用以下依赖项 4.x:

<dependency>
    <groupId>org.neo4j.test</groupId>
    <artifactId>neo4j-harness</artifactId>
    <version>4.0.8</version>
    <scope>test</scope>
</dependency>

然后像这样构造您的 JUnit 5 测试:

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.neo4j.harness.Neo4j;
import org.neo4j.harness.Neo4jBuilders;

public class SimpleTest {

    private static Neo4j embeddedDatabaseServer;

    @BeforeAll
    static void initializeNeo4j() {

        embeddedDatabaseServer = Neo4jBuilders.newInProcessBuilder()
            .withDisabledServer() // Don't need Neos HTTP server
            .withFixture(""
                + "CREATE (TheMatrix:Movie {title:'The Matrix', released:1999, tagline:'Welcome to the Real World'})"
            )
            .build();
    }

    @AfterAll
    static void stopNeo4j() {

        embeddedDatabaseServer.close();
    }

    @Test
    void testSomething() {

        try(var tx = embeddedDatabaseServer.databaseManagementService().database("neo4j").beginTx()) {
            var result = tx.execute("MATCH (m:Movie) WHERE m.title = 'The Matrix' RETURN m.released");
            Assertions.assertEquals(1999L, result.next().get("m.released"));
        }
    }
}

当然你也可以打开一个bolt URL到嵌入式实例。 embeddedDatabaseServer.boltURI() 给你一个本地套接字地址。身份验证已关闭。

测试看起来像这样:

@Test
void testSomethingOverBolt() {

    try(var driver = GraphDatabase.driver(embeddedDatabaseServer.boltURI(), AuthTokens.none());
    var session = driver.session()) {
        var result = session.run("MATCH (m:Movie) WHERE m.title = 'The Matrix' RETURN m.released");
        Assertions.assertEquals(1999L, result.next().get("m.released").asLong());
    }
}

当然你需要 org.neo4j.driver:neo4j-java-driver

如果需要嵌入式服务器的 non-static 实例,您可以像这样对整个测试 class 建模:

import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.neo4j.harness.Neo4j;
import org.neo4j.harness.Neo4jBuilders;

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class SimpleTest {

    private final Neo4j embeddedDatabaseServer = Neo4jBuilders.newInProcessBuilder()
            .withDisabledServer() // Don't need Neos HTTP server
        .withFixture(""
            + "CREATE (TheMatrix:Movie {title:'The Matrix', released:1999, tagline:'Welcome to the Real World'})"
        )
        .build();

    @AfterAll
    void stopNeo4j() {

        embeddedDatabaseServer.close();
    }

    @Test
    void whatever() {
    }
}

注意测试 class 和 non-static @AfterAll 方法之上的 @TestInstance(TestInstance.Lifecycle.PER_CLASS)