gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 01:51:07 24 4
gpt4 key购买 nike

在为 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 Model : JUnit 5 User Guide , GitHub
JUnit 5 org.junit.vintage : JUnit 5 User Guide , Test-harness pom.xml
JUnit 5 junit-jupiter-migrationsupport : JUnit 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 但相同的结果不断出现,但没有一个会导致我寻求的结果。

检查 JUnit Jupiter Extensions 并没有发现 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;
}
}

最后剩下的就是使用带有 @ExtendWith@Test 的 Neo4j JUnit 5 扩展模型:
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 类和 JUnit 5 扩展模型类都可以从基类继承,然后在相同的测试工具中可用,我不会感到惊讶; fingers crossed 。显然,大部分基类将从 Neo4j TestRule 类中提取。

最佳答案

最简单的方法可能是根本不使用扩展。
对 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
如果需要嵌入式服务器的非静态实例,您可以像这样对整个测试类进行建模:
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() {
}
}
注意测试类顶部的 @TestInstance(TestInstance.Lifecycle.PER_CLASS) 和非静态 @AfterAll 方法。

关于neo4j - 是否有使用 JUnit 5 扩展模型的 Neo4j 测试工具?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53083858/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com