【发布时间】:2019-04-04 15:34:44
【问题描述】:
在为 Neo4j 编写测试用例时,我想继续使用 JUnit 5 扩展模型,而不是使用 org.junit.vintage 或 junit-jupiter-migrationsupport。目前我只能找到 JUnit 4 的 Neo4j 测试工具,它使用 TestRule 并依赖于 org.junit.vintage 和 junit-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 测试工具,为什么还要创建我自己的。
可能我只是用错误的关键字进行查询,这些关键字只是 neo4j 和 JUnit 5,但相同的结果不断出现,但都没有导致我所寻求的。
检查了JUnit Jupiter Extensions,没有找到 Neo4j。
编辑
概念证明
由于下面的代码只是概念证明,它不会作为公认的答案发布,但希望会在几天内发布。
事实证明,将 JUnit 5 Jupiter Extensions 添加到现有的 JUnit TestRlue 并不是那么糟糕。一路走来有一些艰难的地方,如果你像我一样,不生活和呼吸单一的编程语言或工具集,你必须花一些时间来理解这些精神;如果你问我,那应该是一个 SO 标签。
注意:此代码是Neo4j TestRule 和A Guide to JUnit 5 Extensions 中的一些代码的组合
从 Neo4j 开始 TestRule 只需更改工具即可:
删除TestRule
添加BeforeEachCallback和AfterEachCallback
注意:BeforeEach 和 AfterEach 在 Neo4j 中使用,而不是 BeforeAll 和 AfterAll,因为在创建节点时每次新测试,如果创建新节点与之前的测试相同并且数据库是如果不是新数据库,那么检查节点的 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 类中提取出来的。
【问题讨论】:
-
在即将发布的 Testcontainers 版本中将会有一个 Neo4jTestcontainer。
标签: neo4j junit5 junit5-extension-model