You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@shardingsphere.apache.org by su...@apache.org on 2022/12/22 02:18:05 UTC
[shardingsphere] branch master updated: Use FieldReader and InstanceField instead of reflection api in test cases (#23022)
This is an automated email from the ASF dual-hosted git repository.
sunnianjun pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/shardingsphere.git
The following commit(s) were added to refs/heads/master by this push:
new 47916c32265 Use FieldReader and InstanceField instead of reflection api in test cases (#23022)
47916c32265 is described below
commit 47916c322651196f41393598cac02f36931d09c7
Author: Liang Zhang <zh...@apache.org>
AuthorDate: Thu Dec 22 10:17:53 2022 +0800
Use FieldReader and InstanceField instead of reflection api in test cases (#23022)
* webfont
* Refactor ExecutorExceptionHandlerTest
* Refactor PluginBootServiceTest
* Refactor PipelineContextUtil
* Refactor FixedReplicaWeightReadQueryLoadBalanceAlgorithmTest
* Refactor ConnectionIdGeneratorTest
* Refactor DBCPDataSourcePoolCreatorTest
* Refactor TransactionWeightReadQueryLoadBalanceAlgorithmTest
* Refactor RunnerParameters
* Refactor ShardingTokenGenerateBuilderTest
* Refactor SnowflakeKeyGenerateAlgorithmTest
* Refactor MySQLFrontendEngineTest
* Refactor EncryptTokenGenerateBuilderTest
* Refactor SQLStatementCacheLoaderTest
* Refactor StatementAdapterTest
* Refactor ImportDatabaseConfigurationHandlerTest
* Refactor SeataATShardingSphereTransactionManagerTest
* Refactor YamlShardingSphereDataSourceFactoryTest
---
.../PrometheusPluginBootServiceTest.java | 12 ++++----
.../jaeger/JaegerTracingPluginBootServiceTest.java | 20 ++++++-------
.../OpenTelemetryTracingPluginBootServiceTest.java | 6 ++--
.../OpenTracingPluginBootServiceTest.java | 14 ++++-----
.../zipkin/ZipkinTracingPluginBootServiceTest.java | 20 ++++++-------
.../static/fonts/fontawesome-webfont.eot | Bin 165719 -> 165717 bytes
.../static/fonts/fontawesome-webfont.ttf | Bin 165525 -> 165523 bytes
.../token/EncryptTokenGenerateBuilderTest.java | 22 +++++++-------
...icaWeightReadQueryLoadBalanceAlgorithmTest.java | 7 ++---
...ionWeightReadQueryLoadBalanceAlgorithmTest.java | 7 ++---
.../keygen/SnowflakeKeyGenerateAlgorithmTest.java | 27 +++++++----------
.../pojo/ShardingTokenGenerateBuilderTest.java | 6 ++--
.../type/DBCPDataSourcePoolCreatorTest.java | 8 ++---
.../engine/ExecutorExceptionHandlerTest.java | 6 ++--
.../engine/jdbc/JDBCExecutorCallbackTest.java | 9 +++---
.../parser/cache/SQLStatementCacheLoaderTest.java | 8 ++---
.../token/generator/SQLTokenGeneratorsTest.java | 16 +++++-----
.../spi/type/ordered/OrderedSPIRegistryTest.java | 12 ++++----
.../ordered/cache/OrderedServicesCacheTest.java | 12 ++++----
.../api/ShardingSphereDataSourceFactoryTest.java | 6 ++--
.../YamlShardingSphereDataSourceFactoryTest.java | 8 ++---
.../driver/jdbc/adapter/StatementAdapterTest.java | 8 ++---
...eataATShardingSphereTransactionManagerTest.java | 33 +++++++--------------
.../ImportDatabaseConfigurationHandlerTest.java | 21 +++++--------
.../connection/ConnectionIdGeneratorTest.java | 7 ++---
.../netty/FrontendChannelInboundHandlerTest.java | 9 ++----
.../frontend/mysql/MySQLFrontendEngineTest.java | 7 ++---
.../MySQLAuthenticationHandlerTest.java | 10 ++-----
.../OpenGaussCommandExecutorFactoryTest.java | 10 +++----
.../simple/OpenGaussComQueryExecutorTest.java | 12 ++++----
.../simple/PostgreSQLComQueryExecutorTest.java | 14 ++++-----
.../err/PostgreSQLErrPacketFactoryTest.java | 21 +++++--------
.../framework/runner/param/RunnerParameters.java | 5 ++--
.../pipeline/core/execute/ExecuteEngineTest.java | 10 +++----
.../pipeline/core/util/PipelineContextUtil.java | 10 +++----
35 files changed, 161 insertions(+), 242 deletions(-)
diff --git a/agent/plugins/metrics/type/prometheus/src/test/java/org/apache/shardingsphere/agent/metrics/prometheus/PrometheusPluginBootServiceTest.java b/agent/plugins/metrics/type/prometheus/src/test/java/org/apache/shardingsphere/agent/metrics/prometheus/PrometheusPluginBootServiceTest.java
index b4d570a09fc..69035f5af38 100644
--- a/agent/plugins/metrics/type/prometheus/src/test/java/org/apache/shardingsphere/agent/metrics/prometheus/PrometheusPluginBootServiceTest.java
+++ b/agent/plugins/metrics/type/prometheus/src/test/java/org/apache/shardingsphere/agent/metrics/prometheus/PrometheusPluginBootServiceTest.java
@@ -30,7 +30,7 @@ import org.apache.shardingsphere.mode.manager.standalone.workerid.generator.Stan
import org.apache.shardingsphere.mode.metadata.MetaDataContexts;
import org.apache.shardingsphere.mode.metadata.persist.MetaDataPersistService;
import org.apache.shardingsphere.proxy.backend.context.ProxyContext;
-import org.junit.AfterClass;
+import org.junit.After;
import org.junit.Test;
import java.io.IOException;
@@ -42,11 +42,11 @@ import static org.mockito.Mockito.mock;
public final class PrometheusPluginBootServiceTest extends ProxyContextRestorer {
- private static final PrometheusPluginBootService PROMETHEUS_PLUGIN_BOOT_SERVICE = new PrometheusPluginBootService();
+ private final PrometheusPluginBootService pluginBootService = new PrometheusPluginBootService();
- @AfterClass
- public static void close() {
- PROMETHEUS_PLUGIN_BOOT_SERVICE.close();
+ @After
+ public void close() {
+ pluginBootService.close();
}
@Test
@@ -56,7 +56,7 @@ public final class PrometheusPluginBootServiceTest extends ProxyContextRestorer
new ComputeNodeInstance(mock(InstanceMetaData.class)), new StandaloneWorkerIdGenerator(), new ModeConfiguration("Standalone", null), mock(LockContext.class),
new EventBusContext());
ProxyContext.init(new ContextManager(metaDataContexts, instanceContext));
- PROMETHEUS_PLUGIN_BOOT_SERVICE.start(new PluginConfiguration("localhost", 8090, "", createProperties()), true);
+ pluginBootService.start(new PluginConfiguration("localhost", 8090, "", createProperties()), true);
new Socket().connect(new InetSocketAddress("localhost", 8090));
}
diff --git a/agent/plugins/tracing/type/jaeger/src/test/java/org/apache/shardingsphere/agent/plugin/tracing/jaeger/JaegerTracingPluginBootServiceTest.java b/agent/plugins/tracing/type/jaeger/src/test/java/org/apache/shardingsphere/agent/plugin/tracing/jaeger/JaegerTracingPluginBootServiceTest.java
index d6e58dfe61f..4ecff6d11a0 100644
--- a/agent/plugins/tracing/type/jaeger/src/test/java/org/apache/shardingsphere/agent/plugin/tracing/jaeger/JaegerTracingPluginBootServiceTest.java
+++ b/agent/plugins/tracing/type/jaeger/src/test/java/org/apache/shardingsphere/agent/plugin/tracing/jaeger/JaegerTracingPluginBootServiceTest.java
@@ -22,19 +22,25 @@ import io.opentracing.util.GlobalTracer;
import org.apache.shardingsphere.agent.config.plugin.PluginConfiguration;
import org.junit.After;
import org.junit.Test;
+import org.mockito.internal.util.reflection.InstanceField;
-import java.lang.reflect.Field;
import java.util.Properties;
import static org.junit.Assert.assertTrue;
public final class JaegerTracingPluginBootServiceTest {
- private final JaegerTracingPluginBootService jaegerTracingPluginBootService = new JaegerTracingPluginBootService();
+ private final JaegerTracingPluginBootService pluginBootService = new JaegerTracingPluginBootService();
+
+ @After
+ public void close() throws NoSuchFieldException {
+ pluginBootService.close();
+ new InstanceField(GlobalTracer.class.getDeclaredField("tracer"), GlobalTracer.class).set(NoopTracerFactory.create());
+ }
@Test
public void assertStart() {
- jaegerTracingPluginBootService.start(new PluginConfiguration("localhost", 5775, "", createProperties()), true);
+ pluginBootService.start(new PluginConfiguration("localhost", 5775, "", createProperties()), true);
assertTrue(GlobalTracer.isRegistered());
}
@@ -46,12 +52,4 @@ public final class JaegerTracingPluginBootServiceTest {
result.setProperty("JAEGER_REPORTER_FLUSH_INTERVAL", "1");
return result;
}
-
- @After
- public void close() throws ReflectiveOperationException {
- jaegerTracingPluginBootService.close();
- Field field = GlobalTracer.class.getDeclaredField("tracer");
- field.setAccessible(true);
- field.set(null, NoopTracerFactory.create());
- }
}
diff --git a/agent/plugins/tracing/type/opentelemetry/src/test/java/org/apache/shardingsphere/agent/plugin/tracing/opentelemetry/OpenTelemetryTracingPluginBootServiceTest.java b/agent/plugins/tracing/type/opentelemetry/src/test/java/org/apache/shardingsphere/agent/plugin/tracing/opentelemetry/OpenTelemetryTracingPluginBootServiceTest.java
index 1366d05f4a9..9dcf55305f8 100644
--- a/agent/plugins/tracing/type/opentelemetry/src/test/java/org/apache/shardingsphere/agent/plugin/tracing/opentelemetry/OpenTelemetryTracingPluginBootServiceTest.java
+++ b/agent/plugins/tracing/type/opentelemetry/src/test/java/org/apache/shardingsphere/agent/plugin/tracing/opentelemetry/OpenTelemetryTracingPluginBootServiceTest.java
@@ -28,9 +28,11 @@ import static org.junit.Assert.assertNotNull;
public final class OpenTelemetryTracingPluginBootServiceTest {
+ private final OpenTelemetryTracingPluginBootService pluginBootService = new OpenTelemetryTracingPluginBootService();
+
@Test
public void assertStart() {
- new OpenTelemetryTracingPluginBootService().start(new PluginConfiguration(null, 0, null, createProperties()), true);
+ pluginBootService.start(new PluginConfiguration(null, 0, null, createProperties()), true);
assertNotNull(GlobalOpenTelemetry.getTracerProvider());
assertNotNull(GlobalOpenTelemetry.getTracer("shardingsphere-agent"));
}
@@ -44,7 +46,7 @@ public final class OpenTelemetryTracingPluginBootServiceTest {
@After
public void close() {
- new OpenTelemetryTracingPluginBootService().close();
+ pluginBootService.close();
GlobalOpenTelemetry.resetForTest();
}
}
diff --git a/agent/plugins/tracing/type/opentracing/src/test/java/org/apache/shardingsphere/agent/plugin/tracing/opentracing/OpenTracingPluginBootServiceTest.java b/agent/plugins/tracing/type/opentracing/src/test/java/org/apache/shardingsphere/agent/plugin/tracing/opentracing/OpenTracingPluginBootServiceTest.java
index 12d91e15b26..b54a9847606 100644
--- a/agent/plugins/tracing/type/opentracing/src/test/java/org/apache/shardingsphere/agent/plugin/tracing/opentracing/OpenTracingPluginBootServiceTest.java
+++ b/agent/plugins/tracing/type/opentracing/src/test/java/org/apache/shardingsphere/agent/plugin/tracing/opentracing/OpenTracingPluginBootServiceTest.java
@@ -28,11 +28,16 @@ import static org.junit.Assert.assertTrue;
public final class OpenTracingPluginBootServiceTest {
- private final OpenTracingPluginBootService openTracingPluginBootService = new OpenTracingPluginBootService();
+ private final OpenTracingPluginBootService pluginBootService = new OpenTracingPluginBootService();
+
+ @After
+ public void close() {
+ pluginBootService.close();
+ }
@Test
public void assertStart() {
- openTracingPluginBootService.start(new PluginConfiguration("localhost", 8090, "", createProperties()), true);
+ pluginBootService.start(new PluginConfiguration("localhost", 8090, "", createProperties()), true);
assertTrue(GlobalTracer.isRegistered());
}
@@ -41,9 +46,4 @@ public final class OpenTracingPluginBootServiceTest {
result.setProperty("opentracing-tracer-class-name", "io.opentracing.mock.MockTracer");
return result;
}
-
- @After
- public void close() {
- openTracingPluginBootService.close();
- }
}
diff --git a/agent/plugins/tracing/type/zipkin/src/test/java/org/apache/shardingsphere/agent/plugin/tracing/zipkin/ZipkinTracingPluginBootServiceTest.java b/agent/plugins/tracing/type/zipkin/src/test/java/org/apache/shardingsphere/agent/plugin/tracing/zipkin/ZipkinTracingPluginBootServiceTest.java
index 24ff40a5fed..4069dc06ddd 100644
--- a/agent/plugins/tracing/type/zipkin/src/test/java/org/apache/shardingsphere/agent/plugin/tracing/zipkin/ZipkinTracingPluginBootServiceTest.java
+++ b/agent/plugins/tracing/type/zipkin/src/test/java/org/apache/shardingsphere/agent/plugin/tracing/zipkin/ZipkinTracingPluginBootServiceTest.java
@@ -21,27 +21,25 @@ import brave.Tracing;
import org.apache.shardingsphere.agent.config.plugin.PluginConfiguration;
import org.junit.After;
import org.junit.Test;
+import org.mockito.internal.util.reflection.FieldReader;
-import java.lang.reflect.Field;
import java.util.Properties;
import static org.junit.Assert.assertNotNull;
public final class ZipkinTracingPluginBootServiceTest {
- private final ZipkinTracingPluginBootService zipkinTracingPluginBootService = new ZipkinTracingPluginBootService();
+ private final ZipkinTracingPluginBootService pluginBootService = new ZipkinTracingPluginBootService();
+
+ @After
+ public void close() {
+ pluginBootService.close();
+ }
@Test
public void assertStart() throws ReflectiveOperationException {
- zipkinTracingPluginBootService.start(new PluginConfiguration("localhost", 9441, "", new Properties()), true);
- Field field = ZipkinTracingPluginBootService.class.getDeclaredField("tracing");
- field.setAccessible(true);
- Tracing tracing = (Tracing) field.get(zipkinTracingPluginBootService);
+ pluginBootService.start(new PluginConfiguration("localhost", 9441, "", new Properties()), true);
+ Tracing tracing = (Tracing) new FieldReader(pluginBootService, ZipkinTracingPluginBootService.class.getDeclaredField("tracing")).read();
assertNotNull(tracing.tracer());
}
-
- @After
- public void close() {
- zipkinTracingPluginBootService.close();
- }
}
diff --git a/docs/document/themes/hugo-theme-learn/static/fonts/fontawesome-webfont.eot b/docs/document/themes/hugo-theme-learn/static/fonts/fontawesome-webfont.eot
index 7c8959e8330..7a7921d5a9d 100644
Binary files a/docs/document/themes/hugo-theme-learn/static/fonts/fontawesome-webfont.eot and b/docs/document/themes/hugo-theme-learn/static/fonts/fontawesome-webfont.eot differ
diff --git a/docs/document/themes/hugo-theme-learn/static/fonts/fontawesome-webfont.ttf b/docs/document/themes/hugo-theme-learn/static/fonts/fontawesome-webfont.ttf
index db4b3b1d0a5..2a12e2c5578 100644
Binary files a/docs/document/themes/hugo-theme-learn/static/fonts/fontawesome-webfont.ttf and b/docs/document/themes/hugo-theme-learn/static/fonts/fontawesome-webfont.ttf differ
diff --git a/features/encrypt/core/src/test/java/org/apache/shardingsphere/encrypt/rewrite/token/EncryptTokenGenerateBuilderTest.java b/features/encrypt/core/src/test/java/org/apache/shardingsphere/encrypt/rewrite/token/EncryptTokenGenerateBuilderTest.java
index d2114ca05f5..9d94687ad82 100644
--- a/features/encrypt/core/src/test/java/org/apache/shardingsphere/encrypt/rewrite/token/EncryptTokenGenerateBuilderTest.java
+++ b/features/encrypt/core/src/test/java/org/apache/shardingsphere/encrypt/rewrite/token/EncryptTokenGenerateBuilderTest.java
@@ -17,10 +17,10 @@
package org.apache.shardingsphere.encrypt.rewrite.token;
+import org.apache.shardingsphere.encrypt.rewrite.aware.EncryptRuleAware;
import org.apache.shardingsphere.encrypt.rewrite.token.generator.EncryptOrderByItemTokenGenerator;
import org.apache.shardingsphere.encrypt.rewrite.token.generator.EncryptProjectionTokenGenerator;
import org.apache.shardingsphere.encrypt.rule.EncryptRule;
-import org.apache.shardingsphere.encrypt.rewrite.aware.EncryptRuleAware;
import org.apache.shardingsphere.infra.binder.segment.select.orderby.OrderByItem;
import org.apache.shardingsphere.infra.binder.statement.dml.SelectStatementContext;
import org.apache.shardingsphere.infra.database.DefaultDatabase;
@@ -30,6 +30,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
+import org.mockito.internal.util.reflection.FieldReader;
import org.mockito.junit.MockitoJUnitRunner;
import java.lang.reflect.Field;
@@ -57,36 +58,33 @@ public final class EncryptTokenGenerateBuilderTest {
}
@Test
- public void assertGetSQLTokenGenerators() throws IllegalAccessException {
+ public void assertGetSQLTokenGenerators() {
SelectStatementContext selectStatementContext = mock(SelectStatementContext.class, RETURNS_DEEP_STUBS);
when(selectStatementContext.getAllTables().isEmpty()).thenReturn(false);
when(selectStatementContext.getTablesContext().getTableNames()).thenReturn(Collections.singletonList("table"));
when(selectStatementContext.getOrderByContext().getItems()).thenReturn(Collections.singletonList(mock(OrderByItem.class)));
when(selectStatementContext.getGroupByContext().getItems()).thenReturn(Collections.emptyList());
when(selectStatementContext.getWhereSegments()).thenReturn(Collections.emptyList());
- EncryptTokenGenerateBuilder encryptTokenGenerateBuilder = new EncryptTokenGenerateBuilder(
- encryptRule, selectStatementContext, Collections.emptyList(), DefaultDatabase.LOGIC_NAME);
+ EncryptTokenGenerateBuilder encryptTokenGenerateBuilder = new EncryptTokenGenerateBuilder(encryptRule, selectStatementContext, Collections.emptyList(), DefaultDatabase.LOGIC_NAME);
Collection<SQLTokenGenerator> sqlTokenGenerators = encryptTokenGenerateBuilder.getSQLTokenGenerators();
assertThat(sqlTokenGenerators.size(), is(2));
Iterator<SQLTokenGenerator> iterator = sqlTokenGenerators.iterator();
SQLTokenGenerator item1 = iterator.next();
assertThat(item1, instanceOf(EncryptProjectionTokenGenerator.class));
- assertSqlTokenGenerator(item1);
+ assertSQLTokenGenerator(item1);
SQLTokenGenerator item2 = iterator.next();
assertThat(item2, instanceOf(EncryptOrderByItemTokenGenerator.class));
- assertSqlTokenGenerator(item2);
+ assertSQLTokenGenerator(item2);
}
- private void assertSqlTokenGenerator(final SQLTokenGenerator sqlTokenGenerator) throws IllegalAccessException {
+ private void assertSQLTokenGenerator(final SQLTokenGenerator sqlTokenGenerator) {
if (sqlTokenGenerator instanceof EncryptRuleAware) {
assertField(sqlTokenGenerator, encryptRule, "encryptRule");
}
}
- private void assertField(final SQLTokenGenerator sqlTokenGenerator, final Object filedInstance, final String fieldName) throws IllegalAccessException {
- Field field = findField(sqlTokenGenerator.getClass(), fieldName, filedInstance.getClass());
- field.setAccessible(true);
- assertThat(field.get(sqlTokenGenerator), is(filedInstance));
+ private void assertField(final SQLTokenGenerator sqlTokenGenerator, final Object filedInstance, final String fieldName) {
+ assertThat(new FieldReader(sqlTokenGenerator, findField(sqlTokenGenerator.getClass(), fieldName, filedInstance.getClass())).read(), is(filedInstance));
}
private Field findField(final Class<?> clazz, final String fieldName, final Class<?> fieldType) {
@@ -99,6 +97,6 @@ public final class EncryptTokenGenerateBuilderTest {
}
searchClass = searchClass.getSuperclass();
}
- throw new IllegalStateException("No such field in class");
+ throw new IllegalStateException("No such field in class.");
}
}
diff --git a/features/readwrite-splitting/core/src/test/java/org/apache/shardingsphere/readwritesplitting/algorithm/loadbalance/FixedReplicaWeightReadQueryLoadBalanceAlgorithmTest.java b/features/readwrite-splitting/core/src/test/java/org/apache/shardingsphere/readwritesplitting/algorithm/loadbalance/FixedReplicaWeightReadQueryLoadBalanceAlgorithmTest.java
index 76b7c31c38e..d7a0c5f59c3 100644
--- a/features/readwrite-splitting/core/src/test/java/org/apache/shardingsphere/readwritesplitting/algorithm/loadbalance/FixedReplicaWeightReadQueryLoadBalanceAlgorithmTest.java
+++ b/features/readwrite-splitting/core/src/test/java/org/apache/shardingsphere/readwritesplitting/algorithm/loadbalance/FixedReplicaWeightReadQueryLoadBalanceAlgorithmTest.java
@@ -23,8 +23,8 @@ import org.apache.shardingsphere.readwritesplitting.factory.ReadQueryLoadBalance
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
+import org.mockito.internal.util.reflection.FieldReader;
-import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
@@ -38,13 +38,10 @@ import static org.junit.Assert.assertTrue;
public final class FixedReplicaWeightReadQueryLoadBalanceAlgorithmTest {
- @SuppressWarnings("rawtypes")
@Before
@After
public void reset() throws NoSuchFieldException, IllegalAccessException {
- Field accuracyThresholdField = FixedReplicaWeightReadQueryLoadBalanceAlgorithm.class.getDeclaredField("WEIGHT_MAP");
- accuracyThresholdField.setAccessible(true);
- ((Map) accuracyThresholdField.get(FixedReplicaWeightReadQueryLoadBalanceAlgorithm.class)).clear();
+ ((Map<?, ?>) new FieldReader(FixedReplicaWeightReadQueryLoadBalanceAlgorithm.class, FixedReplicaWeightReadQueryLoadBalanceAlgorithm.class.getDeclaredField("WEIGHT_MAP")).read()).clear();
}
@Test
diff --git a/features/readwrite-splitting/core/src/test/java/org/apache/shardingsphere/readwritesplitting/algorithm/loadbalance/TransactionWeightReadQueryLoadBalanceAlgorithmTest.java b/features/readwrite-splitting/core/src/test/java/org/apache/shardingsphere/readwritesplitting/algorithm/loadbalance/TransactionWeightReadQueryLoadBalanceAlgorithmTest.java
index 9e2e2fb5156..392fccf12e6 100644
--- a/features/readwrite-splitting/core/src/test/java/org/apache/shardingsphere/readwritesplitting/algorithm/loadbalance/TransactionWeightReadQueryLoadBalanceAlgorithmTest.java
+++ b/features/readwrite-splitting/core/src/test/java/org/apache/shardingsphere/readwritesplitting/algorithm/loadbalance/TransactionWeightReadQueryLoadBalanceAlgorithmTest.java
@@ -23,8 +23,8 @@ import org.apache.shardingsphere.readwritesplitting.factory.ReadQueryLoadBalance
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
+import org.mockito.internal.util.reflection.FieldReader;
-import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@@ -38,13 +38,10 @@ import static org.junit.Assert.assertTrue;
public final class TransactionWeightReadQueryLoadBalanceAlgorithmTest {
- @SuppressWarnings("rawtypes")
@Before
@After
public void reset() throws NoSuchFieldException, IllegalAccessException {
- Field accuracyThresholdField = TransactionWeightReadQueryLoadBalanceAlgorithm.class.getDeclaredField("WEIGHT_MAP");
- accuracyThresholdField.setAccessible(true);
- ((Map) accuracyThresholdField.get(TransactionWeightReadQueryLoadBalanceAlgorithm.class)).clear();
+ ((Map<?, ?>) new FieldReader(TransactionWeightReadQueryLoadBalanceAlgorithm.class, TransactionWeightReadQueryLoadBalanceAlgorithm.class.getDeclaredField("WEIGHT_MAP")).read()).clear();
}
@Test
diff --git a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/algorithm/keygen/SnowflakeKeyGenerateAlgorithmTest.java b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/algorithm/keygen/SnowflakeKeyGenerateAlgorithmTest.java
index db2b501bbba..67f929ba349 100644
--- a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/algorithm/keygen/SnowflakeKeyGenerateAlgorithmTest.java
+++ b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/algorithm/keygen/SnowflakeKeyGenerateAlgorithmTest.java
@@ -19,20 +19,21 @@ package org.apache.shardingsphere.sharding.algorithm.keygen;
import lombok.SneakyThrows;
import org.apache.shardingsphere.infra.config.algorithm.AlgorithmConfiguration;
-import org.apache.shardingsphere.infra.instance.InstanceContextAware;
import org.apache.shardingsphere.infra.config.mode.ModeConfiguration;
-import org.apache.shardingsphere.infra.util.eventbus.EventBusContext;
import org.apache.shardingsphere.infra.instance.ComputeNodeInstance;
import org.apache.shardingsphere.infra.instance.InstanceContext;
+import org.apache.shardingsphere.infra.instance.InstanceContextAware;
import org.apache.shardingsphere.infra.instance.metadata.InstanceMetaData;
import org.apache.shardingsphere.infra.lock.LockContext;
+import org.apache.shardingsphere.infra.util.eventbus.EventBusContext;
import org.apache.shardingsphere.sharding.algorithm.keygen.fixture.FixedTimeService;
import org.apache.shardingsphere.sharding.algorithm.keygen.fixture.WorkerIdGeneratorFixture;
import org.apache.shardingsphere.sharding.factory.KeyGenerateAlgorithmFactory;
import org.apache.shardingsphere.sharding.spi.KeyGenerateAlgorithm;
import org.junit.Test;
+import org.mockito.internal.util.reflection.FieldReader;
+import org.mockito.internal.util.reflection.InstanceField;
-import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
@@ -180,7 +181,7 @@ public final class SnowflakeKeyGenerateAlgorithmTest {
((InstanceContextAware) algorithm).setInstanceContext(INSTANCE);
}
setLastMilliseconds(algorithm, timeService.getCurrentMillis());
- setSequence(algorithm, (1 << DEFAULT_SEQUENCE_BITS) - 1);
+ setSequence(algorithm, (1 << DEFAULT_SEQUENCE_BITS) - 1L);
List<Comparable<?>> expected = Arrays.asList(4194304L, 4194305L, 4194306L, 8388608L, 8388609L, 8388610L, 12582913L, 12582914L, 12582915L, 16777216L);
List<Comparable<?>> actual = new ArrayList<>(DEFAULT_KEY_AMOUNT);
for (int i = 0; i < DEFAULT_KEY_AMOUNT; i++) {
@@ -189,18 +190,14 @@ public final class SnowflakeKeyGenerateAlgorithmTest {
assertThat(actual, is(expected));
}
- @SneakyThrows(ReflectiveOperationException.class)
+ @SneakyThrows(NoSuchFieldException.class)
private void setLastMilliseconds(final KeyGenerateAlgorithm algorithm, final Number value) {
- Field lastMilliseconds = SnowflakeKeyGenerateAlgorithm.class.getDeclaredField("lastMilliseconds");
- lastMilliseconds.setAccessible(true);
- lastMilliseconds.set(algorithm, value);
+ new InstanceField(SnowflakeKeyGenerateAlgorithm.class.getDeclaredField("lastMilliseconds"), algorithm).set(value);
}
- @SneakyThrows(ReflectiveOperationException.class)
+ @SneakyThrows(NoSuchFieldException.class)
private void setSequence(final KeyGenerateAlgorithm algorithm, final Number value) {
- Field sequence = SnowflakeKeyGenerateAlgorithm.class.getDeclaredField("sequence");
- sequence.setAccessible(true);
- sequence.set(algorithm, value);
+ new InstanceField(SnowflakeKeyGenerateAlgorithm.class.getDeclaredField("sequence"), algorithm).set(value);
}
@Test(expected = IllegalArgumentException.class)
@@ -236,12 +233,10 @@ public final class SnowflakeKeyGenerateAlgorithmTest {
}
@Test
- public void assertSetMaxTolerateTimeDifferenceMilliseconds() throws NoSuchFieldException, IllegalAccessException {
+ public void assertSetMaxTolerateTimeDifferenceMilliseconds() throws NoSuchFieldException {
Properties props = new Properties();
props.setProperty("max-tolerate-time-difference-milliseconds", String.valueOf(1));
KeyGenerateAlgorithm algorithm = KeyGenerateAlgorithmFactory.newInstance(new AlgorithmConfiguration("SNOWFLAKE", props));
- Field field = algorithm.getClass().getDeclaredField("props");
- field.setAccessible(true);
- assertThat(((Properties) field.get(algorithm)).getProperty("max-tolerate-time-difference-milliseconds"), is("1"));
+ assertThat(((Properties) new FieldReader(algorithm, algorithm.getClass().getDeclaredField("props")).read()).getProperty("max-tolerate-time-difference-milliseconds"), is("1"));
}
}
diff --git a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/rewrite/token/pojo/ShardingTokenGenerateBuilderTest.java b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/rewrite/token/pojo/ShardingTokenGenerateBuilderTest.java
index 4866bbee757..19859ea31ae 100644
--- a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/rewrite/token/pojo/ShardingTokenGenerateBuilderTest.java
+++ b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/rewrite/token/pojo/ShardingTokenGenerateBuilderTest.java
@@ -29,8 +29,8 @@ import org.apache.shardingsphere.sharding.rule.ShardingRule;
import org.apache.shardingsphere.sharding.rule.aware.ShardingRuleAware;
import org.junit.Before;
import org.junit.Test;
+import org.mockito.internal.util.reflection.FieldReader;
-import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Iterator;
@@ -86,8 +86,6 @@ public final class ShardingTokenGenerateBuilderTest {
}
private void assertField(final SQLTokenGenerator sqlTokenGenerator, final Object filedInstance, final String fieldName) throws Exception {
- Field field = sqlTokenGenerator.getClass().getDeclaredField(fieldName);
- field.setAccessible(true);
- assertThat(field.get(sqlTokenGenerator), is(filedInstance));
+ assertThat(new FieldReader(sqlTokenGenerator, sqlTokenGenerator.getClass().getDeclaredField(fieldName)).read(), is(filedInstance));
}
}
diff --git a/infra/common/src/test/java/org/apache/shardingsphere/infra/datasource/pool/creator/type/DBCPDataSourcePoolCreatorTest.java b/infra/common/src/test/java/org/apache/shardingsphere/infra/datasource/pool/creator/type/DBCPDataSourcePoolCreatorTest.java
index 6f59ec83725..d75bd1949b6 100644
--- a/infra/common/src/test/java/org/apache/shardingsphere/infra/datasource/pool/creator/type/DBCPDataSourcePoolCreatorTest.java
+++ b/infra/common/src/test/java/org/apache/shardingsphere/infra/datasource/pool/creator/type/DBCPDataSourcePoolCreatorTest.java
@@ -23,8 +23,8 @@ import org.apache.shardingsphere.infra.datasource.pool.creator.DataSourcePoolCre
import org.apache.shardingsphere.infra.datasource.props.DataSourceProperties;
import org.apache.shardingsphere.test.fixture.jdbc.MockedDataSource;
import org.junit.Test;
+import org.mockito.internal.util.reflection.FieldReader;
-import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
@@ -60,10 +60,8 @@ public final class DBCPDataSourcePoolCreatorTest {
return result;
}
- @SneakyThrows(ReflectiveOperationException.class)
+ @SneakyThrows(NoSuchFieldException.class)
private Properties getConnectionProperties(final BasicDataSource actual) {
- Field field = actual.getClass().getDeclaredField("connectionProperties");
- field.setAccessible(true);
- return (Properties) field.get(actual);
+ return (Properties) new FieldReader(actual, BasicDataSource.class.getDeclaredField("connectionProperties")).read();
}
}
diff --git a/infra/executor/src/test/java/org/apache/shardingsphere/infra/executor/sql/execute/engine/ExecutorExceptionHandlerTest.java b/infra/executor/src/test/java/org/apache/shardingsphere/infra/executor/sql/execute/engine/ExecutorExceptionHandlerTest.java
index f8c8162745d..75d9340e51d 100644
--- a/infra/executor/src/test/java/org/apache/shardingsphere/infra/executor/sql/execute/engine/ExecutorExceptionHandlerTest.java
+++ b/infra/executor/src/test/java/org/apache/shardingsphere/infra/executor/sql/execute/engine/ExecutorExceptionHandlerTest.java
@@ -19,8 +19,8 @@ package org.apache.shardingsphere.infra.executor.sql.execute.engine;
import org.junit.After;
import org.junit.Test;
+import org.mockito.internal.util.reflection.FieldReader;
-import java.lang.reflect.Field;
import java.sql.SQLException;
import static org.junit.Assert.assertFalse;
@@ -30,9 +30,7 @@ public final class ExecutorExceptionHandlerTest {
@After
public void tearDown() throws NoSuchFieldException, IllegalAccessException {
- Field field = SQLExecutorExceptionHandler.class.getDeclaredField("IS_EXCEPTION_THROWN");
- field.setAccessible(true);
- ((ThreadLocal) field.get(SQLExecutorExceptionHandler.class)).remove();
+ ((ThreadLocal<?>) new FieldReader(SQLExecutorExceptionHandler.class, SQLExecutorExceptionHandler.class.getDeclaredField("IS_EXCEPTION_THROWN")).read()).remove();
}
@Test(expected = SQLException.class)
diff --git a/infra/executor/src/test/java/org/apache/shardingsphere/infra/executor/sql/execute/engine/jdbc/JDBCExecutorCallbackTest.java b/infra/executor/src/test/java/org/apache/shardingsphere/infra/executor/sql/execute/engine/jdbc/JDBCExecutorCallbackTest.java
index 4f44967d0e7..ebafaa0cfce 100644
--- a/infra/executor/src/test/java/org/apache/shardingsphere/infra/executor/sql/execute/engine/jdbc/JDBCExecutorCallbackTest.java
+++ b/infra/executor/src/test/java/org/apache/shardingsphere/infra/executor/sql/execute/engine/jdbc/JDBCExecutorCallbackTest.java
@@ -20,22 +20,22 @@ package org.apache.shardingsphere.infra.executor.sql.execute.engine.jdbc;
import org.apache.shardingsphere.infra.database.metadata.DataSourceMetaData;
import org.apache.shardingsphere.infra.database.type.DatabaseType;
import org.apache.shardingsphere.infra.database.type.DatabaseTypeFactory;
-import org.apache.shardingsphere.infra.util.eventbus.EventBusContext;
import org.apache.shardingsphere.infra.executor.sql.context.ExecutionUnit;
import org.apache.shardingsphere.infra.executor.sql.context.SQLUnit;
import org.apache.shardingsphere.infra.executor.sql.execute.engine.ConnectionMode;
import org.apache.shardingsphere.infra.executor.sql.execute.engine.SQLExecutorExceptionHandler;
import org.apache.shardingsphere.infra.executor.sql.execute.engine.driver.jdbc.JDBCExecutionUnit;
import org.apache.shardingsphere.infra.executor.sql.execute.engine.driver.jdbc.JDBCExecutorCallback;
+import org.apache.shardingsphere.infra.util.eventbus.EventBusContext;
import org.apache.shardingsphere.sql.parser.sql.common.statement.SQLStatement;
import org.apache.shardingsphere.sql.parser.sql.common.statement.dml.SelectStatement;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
+import org.mockito.internal.util.reflection.FieldReader;
import org.mockito.junit.MockitoJUnitRunner;
-import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.PreparedStatement;
@@ -92,9 +92,8 @@ public final class JDBCExecutorCallbackTest {
return Optional.empty();
}
};
- Field field = JDBCExecutorCallback.class.getDeclaredField("CACHED_DATASOURCE_METADATA");
- field.setAccessible(true);
- Map<String, DataSourceMetaData> cachedDataSourceMetaData = (Map<String, DataSourceMetaData>) field.get(jdbcExecutorCallback);
+ Map<String, DataSourceMetaData> cachedDataSourceMetaData = (Map<String, DataSourceMetaData>) new FieldReader(
+ jdbcExecutorCallback, JDBCExecutorCallback.class.getDeclaredField("CACHED_DATASOURCE_METADATA")).read();
jdbcExecutorCallback.execute(units, true, Collections.emptyMap());
assertThat(cachedDataSourceMetaData.size(), is(1));
jdbcExecutorCallback.execute(units, true, Collections.emptyMap());
diff --git a/infra/parser/src/test/java/org/apache/shardingsphere/infra/parser/cache/SQLStatementCacheLoaderTest.java b/infra/parser/src/test/java/org/apache/shardingsphere/infra/parser/cache/SQLStatementCacheLoaderTest.java
index bdd4184ab85..ecaf723814d 100644
--- a/infra/parser/src/test/java/org/apache/shardingsphere/infra/parser/cache/SQLStatementCacheLoaderTest.java
+++ b/infra/parser/src/test/java/org/apache/shardingsphere/infra/parser/cache/SQLStatementCacheLoaderTest.java
@@ -21,8 +21,7 @@ import org.apache.shardingsphere.infra.parser.sql.SQLStatementParserExecutor;
import org.apache.shardingsphere.sql.parser.api.CacheOption;
import org.apache.shardingsphere.sql.parser.sql.common.statement.SQLStatement;
import org.junit.Test;
-
-import java.lang.reflect.Field;
+import org.mockito.internal.util.reflection.InstanceField;
import static org.hamcrest.CoreMatchers.isA;
import static org.hamcrest.MatcherAssert.assertThat;
@@ -36,11 +35,8 @@ public final class SQLStatementCacheLoaderTest {
@Test
public void assertSQLStatementCacheLoad() throws ReflectiveOperationException {
SQLStatementCacheLoader sqlStatementCacheLoader = new SQLStatementCacheLoader("MySQL", new CacheOption(128, 1024L), false);
- Field sqlStatementParserExecutorField = sqlStatementCacheLoader.getClass().getDeclaredField("sqlStatementParserExecutor");
SQLStatementParserExecutor executor = mock(SQLStatementParserExecutor.class, RETURNS_DEEP_STUBS);
- sqlStatementParserExecutorField.setAccessible(true);
- sqlStatementParserExecutorField.set(sqlStatementCacheLoader, executor);
+ new InstanceField(sqlStatementCacheLoader.getClass().getDeclaredField("sqlStatementParserExecutor"), sqlStatementCacheLoader).set(executor);
assertThat(sqlStatementCacheLoader.load(SQL), isA(SQLStatement.class));
- sqlStatementParserExecutorField.setAccessible(false);
}
}
diff --git a/infra/rewrite/src/test/java/org/apache/shardingsphere/infra/rewrite/sql/token/generator/SQLTokenGeneratorsTest.java b/infra/rewrite/src/test/java/org/apache/shardingsphere/infra/rewrite/sql/token/generator/SQLTokenGeneratorsTest.java
index f45680d5f33..2bb5658edba 100644
--- a/infra/rewrite/src/test/java/org/apache/shardingsphere/infra/rewrite/sql/token/generator/SQLTokenGeneratorsTest.java
+++ b/infra/rewrite/src/test/java/org/apache/shardingsphere/infra/rewrite/sql/token/generator/SQLTokenGeneratorsTest.java
@@ -22,8 +22,8 @@ import org.apache.shardingsphere.infra.context.ConnectionContext;
import org.apache.shardingsphere.infra.metadata.database.schema.decorator.model.ShardingSphereSchema;
import org.apache.shardingsphere.infra.rewrite.sql.token.pojo.SQLToken;
import org.junit.Test;
+import org.mockito.internal.util.reflection.FieldReader;
-import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
@@ -41,9 +41,9 @@ import static org.mockito.Mockito.when;
public final class SQLTokenGeneratorsTest {
@Test
- public void assertAddAllWithList() throws Exception {
+ public void assertAddAllWithList() throws NoSuchFieldException {
SQLTokenGenerators sqlTokenGenerators = new SQLTokenGenerators();
- Map<Class<?>, SQLTokenGenerator> actualSqlTokenGeneratorsMap = getSqlTokenGeneratorsMap(sqlTokenGenerators);
+ Map<Class<?>, SQLTokenGenerator> actualSqlTokenGeneratorsMap = getSQLTokenGeneratorsMap(sqlTokenGenerators);
SQLTokenGenerator mockSqlTokenGenerator = mock(SQLTokenGenerator.class);
sqlTokenGenerators.addAll(Collections.singleton(mockSqlTokenGenerator));
assertThat(actualSqlTokenGeneratorsMap.size(), is(1));
@@ -52,7 +52,7 @@ public final class SQLTokenGeneratorsTest {
}
@Test
- public void assertAddAllWithSameClass() throws Exception {
+ public void assertAddAllWithSameClass() throws NoSuchFieldException {
SQLTokenGenerators sqlTokenGenerators = new SQLTokenGenerators();
SQLTokenGenerator expectedSqlTokenGenerator = mock(SQLTokenGenerator.class);
SQLTokenGenerator unexpectedSqlTokenGenerator = mock(SQLTokenGenerator.class);
@@ -60,7 +60,7 @@ public final class SQLTokenGeneratorsTest {
collection.add(expectedSqlTokenGenerator);
collection.add(unexpectedSqlTokenGenerator);
sqlTokenGenerators.addAll(collection);
- Map<Class<?>, SQLTokenGenerator> actualSqlTokenGeneratorsMap = getSqlTokenGeneratorsMap(sqlTokenGenerators);
+ Map<Class<?>, SQLTokenGenerator> actualSqlTokenGeneratorsMap = getSQLTokenGeneratorsMap(sqlTokenGenerators);
assertThat(actualSqlTokenGeneratorsMap.size(), is(1));
SQLTokenGenerator actualSqlTokenGenerator = actualSqlTokenGeneratorsMap.get(expectedSqlTokenGenerator.getClass());
assertThat(actualSqlTokenGenerator, is(expectedSqlTokenGenerator));
@@ -95,9 +95,7 @@ public final class SQLTokenGeneratorsTest {
}
@SuppressWarnings("unchecked")
- private Map<Class<?>, SQLTokenGenerator> getSqlTokenGeneratorsMap(final SQLTokenGenerators sqlTokenGenerators) throws NoSuchFieldException, IllegalAccessException {
- Field field = sqlTokenGenerators.getClass().getDeclaredField("sqlTokenGenerators");
- field.setAccessible(true);
- return (Map<Class<?>, SQLTokenGenerator>) field.get(sqlTokenGenerators);
+ private Map<Class<?>, SQLTokenGenerator> getSQLTokenGeneratorsMap(final SQLTokenGenerators sqlTokenGenerators) throws NoSuchFieldException {
+ return (Map<Class<?>, SQLTokenGenerator>) new FieldReader(sqlTokenGenerators, sqlTokenGenerators.getClass().getDeclaredField("sqlTokenGenerators")).read();
}
}
diff --git a/infra/util/src/test/java/org/apache/shardingsphere/infra/util/spi/type/ordered/OrderedSPIRegistryTest.java b/infra/util/src/test/java/org/apache/shardingsphere/infra/util/spi/type/ordered/OrderedSPIRegistryTest.java
index 5962f8c3ca0..9d28be957bd 100644
--- a/infra/util/src/test/java/org/apache/shardingsphere/infra/util/spi/type/ordered/OrderedSPIRegistryTest.java
+++ b/infra/util/src/test/java/org/apache/shardingsphere/infra/util/spi/type/ordered/OrderedSPIRegistryTest.java
@@ -18,16 +18,16 @@
package org.apache.shardingsphere.infra.util.spi.type.ordered;
import org.apache.shardingsphere.infra.util.spi.ShardingSphereServiceLoader;
+import org.apache.shardingsphere.infra.util.spi.type.ordered.cache.OrderedServicesCache;
import org.apache.shardingsphere.infra.util.spi.type.ordered.fixture.OrderedInterfaceFixture;
-import org.apache.shardingsphere.infra.util.spi.type.ordered.fixture.impl.OrderedInterfaceFixtureImpl;
import org.apache.shardingsphere.infra.util.spi.type.ordered.fixture.OrderedSPIFixture;
+import org.apache.shardingsphere.infra.util.spi.type.ordered.fixture.impl.OrderedInterfaceFixtureImpl;
import org.apache.shardingsphere.infra.util.spi.type.ordered.fixture.impl.OrderedSPIFixtureImpl;
-import org.apache.shardingsphere.infra.util.spi.type.ordered.cache.OrderedServicesCache;
import org.junit.After;
import org.junit.Test;
+import org.mockito.internal.util.reflection.InstanceField;
import java.lang.ref.SoftReference;
-import java.lang.reflect.Field;
import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -43,10 +43,8 @@ public final class OrderedSPIRegistryTest {
}
@After
- public void cleanCache() throws NoSuchFieldException, IllegalAccessException {
- Field field = OrderedServicesCache.class.getDeclaredField("cache");
- field.setAccessible(true);
- field.set(null, new SoftReference<>(new ConcurrentHashMap<>()));
+ public void cleanCache() throws NoSuchFieldException {
+ new InstanceField(OrderedServicesCache.class.getDeclaredField("cache"), OrderedServicesCache.class).set(new SoftReference<>(new ConcurrentHashMap<>()));
}
@SuppressWarnings("rawtypes")
diff --git a/infra/util/src/test/java/org/apache/shardingsphere/infra/util/spi/type/ordered/cache/OrderedServicesCacheTest.java b/infra/util/src/test/java/org/apache/shardingsphere/infra/util/spi/type/ordered/cache/OrderedServicesCacheTest.java
index 4e24fc4696a..b75c60ac950 100644
--- a/infra/util/src/test/java/org/apache/shardingsphere/infra/util/spi/type/ordered/cache/OrderedServicesCacheTest.java
+++ b/infra/util/src/test/java/org/apache/shardingsphere/infra/util/spi/type/ordered/cache/OrderedServicesCacheTest.java
@@ -19,14 +19,14 @@ package org.apache.shardingsphere.infra.util.spi.type.ordered.cache;
import org.apache.shardingsphere.infra.util.spi.ShardingSphereServiceLoader;
import org.apache.shardingsphere.infra.util.spi.type.ordered.fixture.OrderedInterfaceFixture;
-import org.apache.shardingsphere.infra.util.spi.type.ordered.fixture.impl.OrderedInterfaceFixtureImpl;
import org.apache.shardingsphere.infra.util.spi.type.ordered.fixture.OrderedSPIFixture;
+import org.apache.shardingsphere.infra.util.spi.type.ordered.fixture.impl.OrderedInterfaceFixtureImpl;
import org.apache.shardingsphere.infra.util.spi.type.ordered.fixture.impl.OrderedSPIFixtureImpl;
import org.junit.After;
import org.junit.Test;
+import org.mockito.internal.util.reflection.InstanceField;
import java.lang.ref.SoftReference;
-import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
@@ -35,8 +35,8 @@ import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;
import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertFalse;
import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public final class OrderedServicesCacheTest {
@@ -46,10 +46,8 @@ public final class OrderedServicesCacheTest {
}
@After
- public void cleanCache() throws NoSuchFieldException, IllegalAccessException {
- Field field = OrderedServicesCache.class.getDeclaredField("cache");
- field.setAccessible(true);
- field.set(null, new SoftReference<>(new ConcurrentHashMap<>()));
+ public void cleanCache() throws NoSuchFieldException {
+ new InstanceField(OrderedServicesCache.class.getDeclaredField("cache"), OrderedServicesCache.class).set(new SoftReference<>(new ConcurrentHashMap<>()));
}
@Test
diff --git a/jdbc/core/src/test/java/org/apache/shardingsphere/driver/api/ShardingSphereDataSourceFactoryTest.java b/jdbc/core/src/test/java/org/apache/shardingsphere/driver/api/ShardingSphereDataSourceFactoryTest.java
index 685b4c8c268..0b8aa888f1b 100644
--- a/jdbc/core/src/test/java/org/apache/shardingsphere/driver/api/ShardingSphereDataSourceFactoryTest.java
+++ b/jdbc/core/src/test/java/org/apache/shardingsphere/driver/api/ShardingSphereDataSourceFactoryTest.java
@@ -23,9 +23,9 @@ import org.apache.shardingsphere.infra.config.mode.ModeConfiguration;
import org.apache.shardingsphere.infra.database.DefaultDatabase;
import org.apache.shardingsphere.test.fixture.jdbc.MockedDataSource;
import org.junit.Test;
+import org.mockito.internal.util.reflection.FieldReader;
import javax.sql.DataSource;
-import java.lang.reflect.Field;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.LinkedList;
@@ -92,8 +92,6 @@ public final class ShardingSphereDataSourceFactoryTest {
@SneakyThrows(ReflectiveOperationException.class)
private void assertDataSource(final DataSource actualDataSource, final String expectedDataSourceName) {
- Field field = ShardingSphereDataSource.class.getDeclaredField("databaseName");
- field.setAccessible(true);
- assertThat((String) field.get(actualDataSource), is(expectedDataSourceName));
+ assertThat(new FieldReader(actualDataSource, ShardingSphereDataSource.class.getDeclaredField("databaseName")).read(), is(expectedDataSourceName));
}
}
diff --git a/jdbc/core/src/test/java/org/apache/shardingsphere/driver/api/yaml/YamlShardingSphereDataSourceFactoryTest.java b/jdbc/core/src/test/java/org/apache/shardingsphere/driver/api/yaml/YamlShardingSphereDataSourceFactoryTest.java
index e98cd5acacb..37fb2cfa4c4 100644
--- a/jdbc/core/src/test/java/org/apache/shardingsphere/driver/api/yaml/YamlShardingSphereDataSourceFactoryTest.java
+++ b/jdbc/core/src/test/java/org/apache/shardingsphere/driver/api/yaml/YamlShardingSphereDataSourceFactoryTest.java
@@ -21,13 +21,13 @@ import lombok.SneakyThrows;
import org.apache.shardingsphere.driver.jdbc.core.datasource.ShardingSphereDataSource;
import org.apache.shardingsphere.test.fixture.jdbc.MockedDataSource;
import org.junit.Test;
+import org.mockito.internal.util.reflection.FieldReader;
import javax.sql.DataSource;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
-import java.lang.reflect.Field;
import java.net.URL;
import java.sql.SQLException;
import java.util.HashMap;
@@ -92,10 +92,8 @@ public final class YamlShardingSphereDataSourceFactoryTest {
return result.toString();
}
- @SneakyThrows(ReflectiveOperationException.class)
+ @SneakyThrows(NoSuchFieldException.class)
private void assertDataSource(final DataSource dataSource) {
- Field field = ShardingSphereDataSource.class.getDeclaredField("databaseName");
- field.setAccessible(true);
- assertThat((String) field.get(dataSource), is("logic_db"));
+ assertThat(new FieldReader(dataSource, ShardingSphereDataSource.class.getDeclaredField("databaseName")).read(), is("logic_db"));
}
}
diff --git a/jdbc/core/src/test/java/org/apache/shardingsphere/driver/jdbc/adapter/StatementAdapterTest.java b/jdbc/core/src/test/java/org/apache/shardingsphere/driver/jdbc/adapter/StatementAdapterTest.java
index 6048011b853..3eb50a33c0d 100644
--- a/jdbc/core/src/test/java/org/apache/shardingsphere/driver/jdbc/adapter/StatementAdapterTest.java
+++ b/jdbc/core/src/test/java/org/apache/shardingsphere/driver/jdbc/adapter/StatementAdapterTest.java
@@ -30,8 +30,8 @@ import org.apache.shardingsphere.sqlfederation.rule.builder.DefaultSQLFederation
import org.apache.shardingsphere.traffic.rule.TrafficRule;
import org.apache.shardingsphere.traffic.rule.builder.DefaultTrafficRuleConfigurationBuilder;
import org.junit.Test;
+import org.mockito.internal.util.reflection.InstanceField;
-import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
@@ -259,10 +259,8 @@ public final class StatementAdapterTest {
return result;
}
- @SneakyThrows(ReflectiveOperationException.class)
+ @SneakyThrows(NoSuchFieldException.class)
private void setExecutionContext(final ShardingSphereStatement statement, final ExecutionContext executionContext) {
- Field field = statement.getClass().getDeclaredField("executionContext");
- field.setAccessible(true);
- field.set(statement, executionContext);
+ new InstanceField(statement.getClass().getDeclaredField("executionContext"), statement).set(executionContext);
}
}
diff --git a/kernel/transaction/type/base/seata-at/src/test/java/org/apache/shardingsphere/transaction/base/seata/at/SeataATShardingSphereTransactionManagerTest.java b/kernel/transaction/type/base/seata-at/src/test/java/org/apache/shardingsphere/transaction/base/seata/at/SeataATShardingSphereTransactionManagerTest.java
index 3d5d66cbf74..15556c70e6b 100644
--- a/kernel/transaction/type/base/seata-at/src/test/java/org/apache/shardingsphere/transaction/base/seata/at/SeataATShardingSphereTransactionManagerTest.java
+++ b/kernel/transaction/type/base/seata-at/src/test/java/org/apache/shardingsphere/transaction/base/seata/at/SeataATShardingSphereTransactionManagerTest.java
@@ -40,9 +40,10 @@ import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
+import org.mockito.internal.util.reflection.FieldReader;
+import org.mockito.internal.util.reflection.InstanceField;
import javax.sql.DataSource;
-import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Collections;
@@ -171,35 +172,23 @@ public final class SeataATShardingSphereTransactionManagerTest {
}
}
- @SneakyThrows(ReflectiveOperationException.class)
+ @SneakyThrows(NoSuchFieldException.class)
@SuppressWarnings("unchecked")
private Map<String, DataSource> getDataSourceMap() {
- Field field = seataTransactionManager.getClass().getDeclaredField("dataSourceMap");
- field.setAccessible(true);
- return (Map<String, DataSource>) field.get(seataTransactionManager);
+ return (Map<String, DataSource>) new FieldReader(seataTransactionManager, seataTransactionManager.getClass().getDeclaredField("dataSourceMap")).read();
}
- @SneakyThrows(ReflectiveOperationException.class)
+ @SneakyThrows(NoSuchFieldException.class)
private void setXID(final String xid) {
- Field field = SeataTransactionHolder.get().getClass().getDeclaredField("xid");
- field.setAccessible(true);
- field.set(SeataTransactionHolder.get(), xid);
+ new InstanceField(SeataTransactionHolder.get().getClass().getDeclaredField("xid"), SeataTransactionHolder.get()).set(xid);
RootContext.bind(xid);
}
- @SneakyThrows(ReflectiveOperationException.class)
+ @SneakyThrows(NoSuchFieldException.class)
private void releaseRpcClient() {
- Field field = TmNettyRemotingClient.getInstance().getClass().getDeclaredField("initialized");
- field.setAccessible(true);
- field.set(TmNettyRemotingClient.getInstance(), new AtomicBoolean(false));
- field = TmNettyRemotingClient.getInstance().getClass().getDeclaredField("instance");
- field.setAccessible(true);
- field.set(TmNettyRemotingClient.getInstance(), null);
- field = RmNettyRemotingClient.getInstance().getClass().getDeclaredField("initialized");
- field.setAccessible(true);
- field.set(RmNettyRemotingClient.getInstance(), new AtomicBoolean(false));
- field = RmNettyRemotingClient.getInstance().getClass().getDeclaredField("instance");
- field.setAccessible(true);
- field.set(RmNettyRemotingClient.getInstance(), null);
+ new InstanceField(TmNettyRemotingClient.getInstance().getClass().getDeclaredField("initialized"), TmNettyRemotingClient.getInstance()).set(new AtomicBoolean(false));
+ new InstanceField(TmNettyRemotingClient.getInstance().getClass().getDeclaredField("instance"), TmNettyRemotingClient.getInstance()).set(null);
+ new InstanceField(RmNettyRemotingClient.getInstance().getClass().getDeclaredField("initialized"), RmNettyRemotingClient.getInstance()).set(new AtomicBoolean(false));
+ new InstanceField(RmNettyRemotingClient.getInstance().getClass().getDeclaredField("instance"), RmNettyRemotingClient.getInstance()).set(null);
}
}
diff --git a/proxy/backend/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/updatable/ImportDatabaseConfigurationHandlerTest.java b/proxy/backend/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/updatable/ImportDatabaseConfigurationHandlerTest.java
index b9ad0eeb50c..6c520f3e8de 100644
--- a/proxy/backend/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/updatable/ImportDatabaseConfigurationHandlerTest.java
+++ b/proxy/backend/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/updatable/ImportDatabaseConfigurationHandlerTest.java
@@ -38,10 +38,10 @@ import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
+import org.mockito.internal.util.reflection.InstanceField;
import org.mockito.junit.MockitoJUnitRunner;
import javax.sql.DataSource;
-import java.lang.reflect.Field;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
@@ -97,9 +97,8 @@ public final class ImportDatabaseConfigurationHandlerTest extends ProxyContextRe
@Test(expected = IllegalStateException.class)
public void assertImportDatabaseExecutorForSharding() throws Exception {
init(sharding);
- Field shardingRuleConfigurationImportCheckerField = importDatabaseConfigurationHandler.getClass().getDeclaredField("shardingRuleConfigurationImportChecker");
- shardingRuleConfigurationImportCheckerField.setAccessible(true);
- shardingRuleConfigurationImportCheckerField.set(importDatabaseConfigurationHandler, shardingRuleConfigurationImportChecker);
+ new InstanceField(importDatabaseConfigurationHandler.getClass().getDeclaredField("shardingRuleConfigurationImportChecker"),
+ importDatabaseConfigurationHandler).set(shardingRuleConfigurationImportChecker);
assertNotNull(ProxyContext.getInstance().getContextManager().getDataSourceMap(sharding));
assertNotNull(ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getDatabase(sharding).getRuleMetaData().getConfigurations());
assertThat(importDatabaseConfigurationHandler.execute(), instanceOf(UpdateResponseHeader.class));
@@ -108,9 +107,8 @@ public final class ImportDatabaseConfigurationHandlerTest extends ProxyContextRe
@Test(expected = IllegalStateException.class)
public void assertImportDatabaseExecutorForReadwriteSplitting() throws Exception {
init(readwriteSplitting);
- Field readwriteSplittingRuleConfigurationImportCheckerField = importDatabaseConfigurationHandler.getClass().getDeclaredField("readwriteSplittingRuleConfigurationImportChecker");
- readwriteSplittingRuleConfigurationImportCheckerField.setAccessible(true);
- readwriteSplittingRuleConfigurationImportCheckerField.set(importDatabaseConfigurationHandler, readwriteSplittingRuleConfigurationImportChecker);
+ new InstanceField(importDatabaseConfigurationHandler.getClass().getDeclaredField("readwriteSplittingRuleConfigurationImportChecker"),
+ importDatabaseConfigurationHandler).set(readwriteSplittingRuleConfigurationImportChecker);
assertNotNull(ProxyContext.getInstance().getContextManager().getDataSourceMap(readwriteSplitting));
assertNotNull(ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getDatabase(readwriteSplitting).getRuleMetaData().getConfigurations());
assertThat(importDatabaseConfigurationHandler.execute(), instanceOf(UpdateResponseHeader.class));
@@ -119,9 +117,8 @@ public final class ImportDatabaseConfigurationHandlerTest extends ProxyContextRe
@Test(expected = IllegalStateException.class)
public void assertImportDatabaseExecutorForDatabaseDiscovery() throws Exception {
init(databaseDiscovery);
- Field databaseDiscoveryRuleConfigurationImportCheckerField = importDatabaseConfigurationHandler.getClass().getDeclaredField("databaseDiscoveryRuleConfigurationImportChecker");
- databaseDiscoveryRuleConfigurationImportCheckerField.setAccessible(true);
- databaseDiscoveryRuleConfigurationImportCheckerField.set(importDatabaseConfigurationHandler, databaseDiscoveryRuleConfigurationImportChecker);
+ new InstanceField(importDatabaseConfigurationHandler.getClass().getDeclaredField("databaseDiscoveryRuleConfigurationImportChecker"),
+ importDatabaseConfigurationHandler).set(databaseDiscoveryRuleConfigurationImportChecker);
assertNotNull(ProxyContext.getInstance().getContextManager().getDataSourceMap(databaseDiscovery));
assertNotNull(ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getDatabase(databaseDiscovery).getRuleMetaData().getConfigurations());
assertThat(importDatabaseConfigurationHandler.execute(), instanceOf(UpdateResponseHeader.class));
@@ -131,9 +128,7 @@ public final class ImportDatabaseConfigurationHandlerTest extends ProxyContextRe
ImportDatabaseConfigurationHandler handler = importDatabaseConfigurationHandler = new ImportDatabaseConfigurationHandler();
handler.init(new ImportDatabaseConfigurationStatement(Objects.requireNonNull(ImportDatabaseConfigurationHandlerTest.class.getResource(featureMap.get(feature))).getPath()),
mock(ConnectionSession.class));
- Field field = importDatabaseConfigurationHandler.getClass().getDeclaredField("validateHandler");
- field.setAccessible(true);
- field.set(importDatabaseConfigurationHandler, validateHandler);
+ new InstanceField(importDatabaseConfigurationHandler.getClass().getDeclaredField("validateHandler"), importDatabaseConfigurationHandler).set(validateHandler);
ContextManager contextManager = mock(ContextManager.class, RETURNS_DEEP_STUBS);
ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS);
when(database.getSchema(DefaultDatabase.LOGIC_NAME)).thenReturn(new ShardingSphereSchema(createTableMap(), Collections.emptyMap()));
diff --git a/proxy/frontend/core/src/test/java/org/apache/shardingsphere/proxy/frontend/connection/ConnectionIdGeneratorTest.java b/proxy/frontend/core/src/test/java/org/apache/shardingsphere/proxy/frontend/connection/ConnectionIdGeneratorTest.java
index 84481827cbf..c1598f95aa8 100644
--- a/proxy/frontend/core/src/test/java/org/apache/shardingsphere/proxy/frontend/connection/ConnectionIdGeneratorTest.java
+++ b/proxy/frontend/core/src/test/java/org/apache/shardingsphere/proxy/frontend/connection/ConnectionIdGeneratorTest.java
@@ -21,8 +21,7 @@ import lombok.SneakyThrows;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
-
-import java.lang.reflect.Field;
+import org.mockito.internal.util.reflection.InstanceField;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
@@ -48,8 +47,6 @@ public final class ConnectionIdGeneratorTest {
@SneakyThrows(ReflectiveOperationException.class)
private void setCurrentConnectionId(final int connectionId) {
- Field field = ConnectionIdGenerator.class.getDeclaredField("currentId");
- field.setAccessible(true);
- field.set(ConnectionIdGenerator.getInstance(), connectionId);
+ new InstanceField(ConnectionIdGenerator.class.getDeclaredField("currentId"), ConnectionIdGenerator.getInstance()).set(connectionId);
}
}
diff --git a/proxy/frontend/core/src/test/java/org/apache/shardingsphere/proxy/frontend/netty/FrontendChannelInboundHandlerTest.java b/proxy/frontend/core/src/test/java/org/apache/shardingsphere/proxy/frontend/netty/FrontendChannelInboundHandlerTest.java
index b275e765c45..6f82f86a71e 100644
--- a/proxy/frontend/core/src/test/java/org/apache/shardingsphere/proxy/frontend/netty/FrontendChannelInboundHandlerTest.java
+++ b/proxy/frontend/core/src/test/java/org/apache/shardingsphere/proxy/frontend/netty/FrontendChannelInboundHandlerTest.java
@@ -38,10 +38,9 @@ import org.junit.runner.RunWith;
import org.mockito.Answers;
import org.mockito.Mock;
import org.mockito.MockedStatic;
+import org.mockito.internal.util.reflection.FieldReader;
import org.mockito.junit.MockitoJUnitRunner;
-import java.lang.reflect.Field;
-
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.ArgumentMatchers.any;
@@ -87,11 +86,9 @@ public final class FrontendChannelInboundHandlerTest {
connectionSession = getConnectionSession();
}
- @SneakyThrows(ReflectiveOperationException.class)
+ @SneakyThrows(NoSuchFieldException.class)
private ConnectionSession getConnectionSession() {
- Field connectionSessionField = FrontendChannelInboundHandler.class.getDeclaredField("connectionSession");
- connectionSessionField.setAccessible(true);
- return (ConnectionSession) connectionSessionField.get(frontendChannelInboundHandler);
+ return (ConnectionSession) new FieldReader(frontendChannelInboundHandler, FrontendChannelInboundHandler.class.getDeclaredField("connectionSession")).read();
}
@Test
diff --git a/proxy/frontend/mysql/src/test/java/org/apache/shardingsphere/proxy/frontend/mysql/MySQLFrontendEngineTest.java b/proxy/frontend/mysql/src/test/java/org/apache/shardingsphere/proxy/frontend/mysql/MySQLFrontendEngineTest.java
index 13ee0cdd1e0..eb9da1a2e7e 100644
--- a/proxy/frontend/mysql/src/test/java/org/apache/shardingsphere/proxy/frontend/mysql/MySQLFrontendEngineTest.java
+++ b/proxy/frontend/mysql/src/test/java/org/apache/shardingsphere/proxy/frontend/mysql/MySQLFrontendEngineTest.java
@@ -51,6 +51,7 @@ import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatcher;
import org.mockito.Mock;
+import org.mockito.internal.util.reflection.InstanceField;
import org.mockito.junit.MockitoJUnitRunner;
import java.lang.reflect.Field;
@@ -100,11 +101,9 @@ public final class MySQLFrontendEngineTest extends ProxyContextRestorer {
when(channel.attr(MySQLConstants.MYSQL_CHARACTER_SET_ATTRIBUTE_KEY)).thenReturn(mock(Attribute.class));
}
- @SneakyThrows(ReflectiveOperationException.class)
+ @SneakyThrows(NoSuchFieldException.class)
private void resetConnectionIdGenerator() {
- Field field = ConnectionIdGenerator.class.getDeclaredField("currentId");
- field.setAccessible(true);
- field.set(ConnectionIdGenerator.getInstance(), 0);
+ new InstanceField(ConnectionIdGenerator.class.getDeclaredField("currentId"), ConnectionIdGenerator.getInstance()).set(0);
mysqlFrontendEngine = new MySQLFrontendEngine();
}
diff --git a/proxy/frontend/mysql/src/test/java/org/apache/shardingsphere/proxy/frontend/mysql/authentication/MySQLAuthenticationHandlerTest.java b/proxy/frontend/mysql/src/test/java/org/apache/shardingsphere/proxy/frontend/mysql/authentication/MySQLAuthenticationHandlerTest.java
index 4614b9a200f..8826dcd682c 100644
--- a/proxy/frontend/mysql/src/test/java/org/apache/shardingsphere/proxy/frontend/mysql/authentication/MySQLAuthenticationHandlerTest.java
+++ b/proxy/frontend/mysql/src/test/java/org/apache/shardingsphere/proxy/frontend/mysql/authentication/MySQLAuthenticationHandlerTest.java
@@ -42,8 +42,8 @@ import org.apache.shardingsphere.proxy.frontend.mysql.authentication.authenticat
import org.apache.shardingsphere.proxy.frontend.mysql.authentication.authenticator.MySQLNativePasswordAuthenticator;
import org.junit.Before;
import org.junit.Test;
+import org.mockito.internal.util.reflection.InstanceField;
-import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
@@ -76,9 +76,7 @@ public final class MySQLAuthenticationHandlerTest extends ProxyContextRestorer {
@SneakyThrows(ReflectiveOperationException.class)
private void initAuthPluginDataForAuthenticationHandler() {
MySQLAuthPluginData authPluginData = new MySQLAuthPluginData(part1, part2);
- Field field = MySQLAuthenticationHandler.class.getDeclaredField("authPluginData");
- field.setAccessible(true);
- field.set(authenticationHandler, authPluginData);
+ new InstanceField(MySQLAuthenticationHandler.class.getDeclaredField("authPluginData"), authenticationHandler).set(authPluginData);
}
@Test
@@ -155,11 +153,9 @@ public final class MySQLAuthenticationHandlerTest extends ProxyContextRestorer {
AuthorityRuleConfiguration ruleConfig = new AuthorityRuleConfiguration(Collections.singletonList(user), new AlgorithmConfiguration("ALL_PERMITTED", new Properties()));
AuthorityRule rule = new AuthorityRuleBuilder().build(ruleConfig, Collections.emptyMap(), mock(InstanceContext.class), mock(ConfigurationProperties.class));
if (!isNeedSuper) {
- Field authorityRegistryField = AuthorityRule.class.getDeclaredField("authorityRegistry");
AuthorityRegistry authorityRegistry = mock(AuthorityRegistry.class);
when(authorityRegistry.findPrivileges(user.getGrantee())).thenReturn(Optional.empty());
- authorityRegistryField.setAccessible(true);
- authorityRegistryField.set(rule, authorityRegistry);
+ new InstanceField(AuthorityRule.class.getDeclaredField("authorityRegistry"), rule).set(authorityRegistry);
}
return new ShardingSphereRuleMetaData(Collections.singletonList(rule));
}
diff --git a/proxy/frontend/opengauss/src/test/java/org/apache/shardingsphere/proxy/frontend/opengauss/command/OpenGaussCommandExecutorFactoryTest.java b/proxy/frontend/opengauss/src/test/java/org/apache/shardingsphere/proxy/frontend/opengauss/command/OpenGaussCommandExecutorFactoryTest.java
index 440ab668e89..f957f21076d 100644
--- a/proxy/frontend/opengauss/src/test/java/org/apache/shardingsphere/proxy/frontend/opengauss/command/OpenGaussCommandExecutorFactoryTest.java
+++ b/proxy/frontend/opengauss/src/test/java/org/apache/shardingsphere/proxy/frontend/opengauss/command/OpenGaussCommandExecutorFactoryTest.java
@@ -48,17 +48,17 @@ import org.apache.shardingsphere.proxy.frontend.postgresql.command.query.extende
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
+import org.mockito.internal.util.reflection.FieldReader;
import org.mockito.junit.MockitoJUnitRunner;
-import java.lang.reflect.Field;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import static org.hamcrest.CoreMatchers.instanceOf;
-import static org.junit.Assert.assertFalse;
import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.assertFalse;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -149,10 +149,8 @@ public final class OpenGaussCommandExecutorFactoryTest {
}
@SuppressWarnings("unchecked")
- @SneakyThrows(ReflectiveOperationException.class)
+ @SneakyThrows(NoSuchFieldException.class)
private static List<CommandExecutor> getExecutorsFromAggregatedCommandExecutor(final PostgreSQLAggregatedCommandExecutor executor) {
- Field field = PostgreSQLAggregatedCommandExecutor.class.getDeclaredField("executors");
- field.setAccessible(true);
- return (List<CommandExecutor>) field.get(executor);
+ return (List<CommandExecutor>) new FieldReader(executor, PostgreSQLAggregatedCommandExecutor.class.getDeclaredField("executors")).read();
}
}
diff --git a/proxy/frontend/opengauss/src/test/java/org/apache/shardingsphere/proxy/frontend/opengauss/command/query/simple/OpenGaussComQueryExecutorTest.java b/proxy/frontend/opengauss/src/test/java/org/apache/shardingsphere/proxy/frontend/opengauss/command/query/simple/OpenGaussComQueryExecutorTest.java
index 2191fda903a..cf16b71732f 100644
--- a/proxy/frontend/opengauss/src/test/java/org/apache/shardingsphere/proxy/frontend/opengauss/command/query/simple/OpenGaussComQueryExecutorTest.java
+++ b/proxy/frontend/opengauss/src/test/java/org/apache/shardingsphere/proxy/frontend/opengauss/command/query/simple/OpenGaussComQueryExecutorTest.java
@@ -24,12 +24,12 @@ import org.apache.shardingsphere.db.protocol.postgresql.packet.command.query.Pos
import org.apache.shardingsphere.db.protocol.postgresql.packet.command.query.PostgreSQLRowDescriptionPacket;
import org.apache.shardingsphere.db.protocol.postgresql.packet.command.query.simple.PostgreSQLComQueryPacket;
import org.apache.shardingsphere.db.protocol.postgresql.packet.generic.PostgreSQLCommandCompletePacket;
+import org.apache.shardingsphere.proxy.backend.handler.ProxyBackendHandler;
import org.apache.shardingsphere.proxy.backend.response.data.QueryResponseRow;
import org.apache.shardingsphere.proxy.backend.response.header.query.QueryHeader;
import org.apache.shardingsphere.proxy.backend.response.header.query.QueryResponseHeader;
import org.apache.shardingsphere.proxy.backend.response.header.update.UpdateResponseHeader;
import org.apache.shardingsphere.proxy.backend.session.ConnectionSession;
-import org.apache.shardingsphere.proxy.backend.handler.ProxyBackendHandler;
import org.apache.shardingsphere.proxy.frontend.command.executor.ResponseType;
import org.apache.shardingsphere.proxy.frontend.postgresql.command.PortalContext;
import org.apache.shardingsphere.sql.parser.sql.common.statement.dml.InsertStatement;
@@ -37,17 +37,17 @@ import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
+import org.mockito.internal.util.reflection.InstanceField;
import org.mockito.junit.MockitoJUnitRunner;
-import java.lang.reflect.Field;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Collections;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertFalse;
import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@@ -73,11 +73,9 @@ public final class OpenGaussComQueryExecutorTest {
setMockFieldIntoExecutor(queryExecutor);
}
- @SneakyThrows(ReflectiveOperationException.class)
+ @SneakyThrows(NoSuchFieldException.class)
private void setMockFieldIntoExecutor(final OpenGaussComQueryExecutor executor) {
- Field field = OpenGaussComQueryExecutor.class.getDeclaredField("proxyBackendHandler");
- field.setAccessible(true);
- field.set(executor, proxyBackendHandler);
+ new InstanceField(OpenGaussComQueryExecutor.class.getDeclaredField("proxyBackendHandler"), executor).set(proxyBackendHandler);
}
@Test
diff --git a/proxy/frontend/postgresql/src/test/java/org/apache/shardingsphere/proxy/frontend/postgresql/command/query/simple/PostgreSQLComQueryExecutorTest.java b/proxy/frontend/postgresql/src/test/java/org/apache/shardingsphere/proxy/frontend/postgresql/command/query/simple/PostgreSQLComQueryExecutorTest.java
index 0c7d6f6216f..b73dda01bcf 100644
--- a/proxy/frontend/postgresql/src/test/java/org/apache/shardingsphere/proxy/frontend/postgresql/command/query/simple/PostgreSQLComQueryExecutorTest.java
+++ b/proxy/frontend/postgresql/src/test/java/org/apache/shardingsphere/proxy/frontend/postgresql/command/query/simple/PostgreSQLComQueryExecutorTest.java
@@ -24,12 +24,12 @@ import org.apache.shardingsphere.db.protocol.postgresql.packet.command.query.Pos
import org.apache.shardingsphere.db.protocol.postgresql.packet.command.query.PostgreSQLRowDescriptionPacket;
import org.apache.shardingsphere.db.protocol.postgresql.packet.command.query.simple.PostgreSQLComQueryPacket;
import org.apache.shardingsphere.db.protocol.postgresql.packet.generic.PostgreSQLCommandCompletePacket;
+import org.apache.shardingsphere.proxy.backend.handler.ProxyBackendHandler;
import org.apache.shardingsphere.proxy.backend.response.data.QueryResponseRow;
-import org.apache.shardingsphere.proxy.backend.response.header.query.QueryResponseHeader;
import org.apache.shardingsphere.proxy.backend.response.header.query.QueryHeader;
+import org.apache.shardingsphere.proxy.backend.response.header.query.QueryResponseHeader;
import org.apache.shardingsphere.proxy.backend.response.header.update.UpdateResponseHeader;
import org.apache.shardingsphere.proxy.backend.session.ConnectionSession;
-import org.apache.shardingsphere.proxy.backend.handler.ProxyBackendHandler;
import org.apache.shardingsphere.proxy.frontend.command.executor.ResponseType;
import org.apache.shardingsphere.proxy.frontend.postgresql.command.PortalContext;
import org.apache.shardingsphere.sql.parser.sql.common.statement.dml.InsertStatement;
@@ -37,17 +37,17 @@ import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
+import org.mockito.internal.util.reflection.InstanceField;
import org.mockito.junit.MockitoJUnitRunner;
-import java.lang.reflect.Field;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Collections;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertFalse;
import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
@@ -73,11 +73,9 @@ public final class PostgreSQLComQueryExecutorTest {
setMockFieldIntoExecutor(queryExecutor);
}
- @SneakyThrows(ReflectiveOperationException.class)
+ @SneakyThrows(NoSuchFieldException.class)
private void setMockFieldIntoExecutor(final PostgreSQLComQueryExecutor executor) {
- Field field = PostgreSQLComQueryExecutor.class.getDeclaredField("proxyBackendHandler");
- field.setAccessible(true);
- field.set(executor, proxyBackendHandler);
+ new InstanceField(PostgreSQLComQueryExecutor.class.getDeclaredField("proxyBackendHandler"), executor).set(proxyBackendHandler);
}
@Test
diff --git a/proxy/frontend/postgresql/src/test/java/org/apache/shardingsphere/proxy/frontend/postgresql/err/PostgreSQLErrPacketFactoryTest.java b/proxy/frontend/postgresql/src/test/java/org/apache/shardingsphere/proxy/frontend/postgresql/err/PostgreSQLErrPacketFactoryTest.java
index 891b07e1945..2ff25e661c1 100644
--- a/proxy/frontend/postgresql/src/test/java/org/apache/shardingsphere/proxy/frontend/postgresql/err/PostgreSQLErrPacketFactoryTest.java
+++ b/proxy/frontend/postgresql/src/test/java/org/apache/shardingsphere/proxy/frontend/postgresql/err/PostgreSQLErrPacketFactoryTest.java
@@ -20,11 +20,11 @@ package org.apache.shardingsphere.proxy.frontend.postgresql.err;
import org.apache.shardingsphere.db.protocol.postgresql.constant.PostgreSQLMessageSeverityLevel;
import org.apache.shardingsphere.db.protocol.postgresql.packet.generic.PostgreSQLErrorResponsePacket;
import org.junit.Test;
+import org.mockito.internal.util.reflection.FieldReader;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
import org.postgresql.util.ServerErrorMessage;
-import java.lang.reflect.Field;
import java.util.Map;
import static org.hamcrest.CoreMatchers.is;
@@ -32,19 +32,18 @@ import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+@SuppressWarnings("unchecked")
public final class PostgreSQLErrPacketFactoryTest {
@Test
- public void assertPSQLExceptionWithServerErrorMessageNotNull() throws NoSuchFieldException, IllegalAccessException {
+ public void assertPSQLExceptionWithServerErrorMessageNotNull() throws NoSuchFieldException {
ServerErrorMessage serverErrorMessage = mock(ServerErrorMessage.class);
when(serverErrorMessage.getSeverity()).thenReturn(PostgreSQLMessageSeverityLevel.FATAL);
when(serverErrorMessage.getSQLState()).thenReturn("sqlState");
when(serverErrorMessage.getMessage()).thenReturn("message");
when(serverErrorMessage.getPosition()).thenReturn(1);
PostgreSQLErrorResponsePacket actual = PostgreSQLErrPacketFactory.newInstance(new PSQLException(serverErrorMessage));
- Field packetField = PostgreSQLErrorResponsePacket.class.getDeclaredField("fields");
- packetField.setAccessible(true);
- Map<Character, String> fields = (Map<Character, String>) packetField.get(actual);
+ Map<Character, String> fields = (Map<Character, String>) new FieldReader(actual, PostgreSQLErrorResponsePacket.class.getDeclaredField("fields")).read();
assertThat(fields.get(PostgreSQLErrorResponsePacket.FIELD_TYPE_SEVERITY), is(PostgreSQLMessageSeverityLevel.FATAL));
assertThat(fields.get(PostgreSQLErrorResponsePacket.FIELD_TYPE_CODE), is("sqlState"));
assertThat(fields.get(PostgreSQLErrorResponsePacket.FIELD_TYPE_MESSAGE), is("message"));
@@ -52,21 +51,17 @@ public final class PostgreSQLErrPacketFactoryTest {
}
@Test
- public void assertPSQLExceptionWithServerErrorMessageIsNull() throws NoSuchFieldException, IllegalAccessException {
+ public void assertPSQLExceptionWithServerErrorMessageIsNull() throws NoSuchFieldException {
PostgreSQLErrorResponsePacket actual = PostgreSQLErrPacketFactory.newInstance(new PSQLException("psqlEx", PSQLState.UNEXPECTED_ERROR, new Exception("test")));
- Field packetField = PostgreSQLErrorResponsePacket.class.getDeclaredField("fields");
- packetField.setAccessible(true);
- Map<Character, String> fields = (Map<Character, String>) packetField.get(actual);
+ Map<Character, String> fields = (Map<Character, String>) new FieldReader(actual, PostgreSQLErrorResponsePacket.class.getDeclaredField("fields")).read();
assertThat(fields.get(PostgreSQLErrorResponsePacket.FIELD_TYPE_CODE), is(PSQLState.UNEXPECTED_ERROR.getState()));
assertThat(fields.get(PostgreSQLErrorResponsePacket.FIELD_TYPE_MESSAGE), is("psqlEx"));
}
@Test
- public void assertRuntimeException() throws NoSuchFieldException, IllegalAccessException {
+ public void assertRuntimeException() throws NoSuchFieldException {
PostgreSQLErrorResponsePacket actual = PostgreSQLErrPacketFactory.newInstance(new RuntimeException("test"));
- Field packetField = PostgreSQLErrorResponsePacket.class.getDeclaredField("fields");
- packetField.setAccessible(true);
- Map<Character, String> fields = (Map<Character, String>) packetField.get(actual);
+ Map<Character, String> fields = (Map<Character, String>) new FieldReader(actual, PostgreSQLErrorResponsePacket.class.getDeclaredField("fields")).read();
assertThat(fields.get(PostgreSQLErrorResponsePacket.FIELD_TYPE_MESSAGE), is("test"));
}
}
diff --git a/test/e2e/suite/src/test/java/org/apache/shardingsphere/test/e2e/framework/runner/param/RunnerParameters.java b/test/e2e/suite/src/test/java/org/apache/shardingsphere/test/e2e/framework/runner/param/RunnerParameters.java
index 66fdf9c4461..1d3a9cf8979 100644
--- a/test/e2e/suite/src/test/java/org/apache/shardingsphere/test/e2e/framework/runner/param/RunnerParameters.java
+++ b/test/e2e/suite/src/test/java/org/apache/shardingsphere/test/e2e/framework/runner/param/RunnerParameters.java
@@ -21,6 +21,7 @@ import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.apache.shardingsphere.test.e2e.framework.param.model.E2ETestParameter;
import org.junit.runners.parameterized.BlockJUnit4ClassRunnerWithParameters;
+import org.mockito.internal.util.reflection.FieldReader;
import java.lang.reflect.Field;
@@ -47,8 +48,6 @@ public final class RunnerParameters {
@SneakyThrows(ReflectiveOperationException.class)
private Object getRunner() {
- Field field = childStatement.getClass().getDeclaredField("val$each");
- field.setAccessible(true);
- return field.get(childStatement);
+ return new FieldReader(childStatement, childStatement.getClass().getDeclaredField("val$each")).read();
}
}
diff --git a/test/it/pipeline/src/test/java/org/apache/shardingsphere/test/it/data/pipeline/core/execute/ExecuteEngineTest.java b/test/it/pipeline/src/test/java/org/apache/shardingsphere/test/it/data/pipeline/core/execute/ExecuteEngineTest.java
index 5b73212c250..1001ba44c24 100644
--- a/test/it/pipeline/src/test/java/org/apache/shardingsphere/test/it/data/pipeline/core/execute/ExecuteEngineTest.java
+++ b/test/it/pipeline/src/test/java/org/apache/shardingsphere/test/it/data/pipeline/core/execute/ExecuteEngineTest.java
@@ -22,8 +22,8 @@ import org.apache.shardingsphere.data.pipeline.api.executor.LifecycleExecutor;
import org.apache.shardingsphere.data.pipeline.core.execute.ExecuteCallback;
import org.apache.shardingsphere.data.pipeline.core.execute.ExecuteEngine;
import org.junit.Test;
+import org.mockito.internal.util.reflection.FieldReader;
-import java.lang.reflect.Field;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
@@ -38,7 +38,7 @@ import static org.mockito.Mockito.verify;
public final class ExecuteEngineTest {
- @Test(timeout = 30000)
+ @Test(timeout = 30000L)
public void assertSubmitAndTaskSucceeded() throws ExecutionException, InterruptedException {
LifecycleExecutor lifecycleExecutor = mock(LifecycleExecutor.class);
ExecuteCallback callback = mock(ExecuteCallback.class);
@@ -50,7 +50,7 @@ public final class ExecuteEngineTest {
verify(callback).onSuccess();
}
- @Test(timeout = 30000)
+ @Test(timeout = 30000L)
public void assertSubmitAndTaskFailed() {
LifecycleExecutor lifecycleExecutor = mock(LifecycleExecutor.class);
RuntimeException expectedException = new RuntimeException("Expected");
@@ -73,9 +73,7 @@ public final class ExecuteEngineTest {
@SneakyThrows({ReflectiveOperationException.class, InterruptedException.class})
private void shutdownAndAwaitTerminal(final ExecuteEngine executeEngine) {
- Field field = ExecuteEngine.class.getDeclaredField("executorService");
- field.setAccessible(true);
- ExecutorService executorService = (ExecutorService) field.get(executeEngine);
+ ExecutorService executorService = (ExecutorService) new FieldReader(executeEngine, ExecuteEngine.class.getDeclaredField("executorService")).read();
executorService.shutdown();
executorService.awaitTermination(30, TimeUnit.SECONDS);
}
diff --git a/test/it/pipeline/src/test/java/org/apache/shardingsphere/test/it/data/pipeline/core/util/PipelineContextUtil.java b/test/it/pipeline/src/test/java/org/apache/shardingsphere/test/it/data/pipeline/core/util/PipelineContextUtil.java
index 48eb188e687..bb2851a8718 100644
--- a/test/it/pipeline/src/test/java/org/apache/shardingsphere/test/it/data/pipeline/core/util/PipelineContextUtil.java
+++ b/test/it/pipeline/src/test/java/org/apache/shardingsphere/test/it/data/pipeline/core/util/PipelineContextUtil.java
@@ -28,7 +28,6 @@ import org.apache.shardingsphere.data.pipeline.core.context.PipelineContext;
import org.apache.shardingsphere.data.pipeline.core.datasource.DefaultPipelineDataSourceManager;
import org.apache.shardingsphere.data.pipeline.core.datasource.PipelineDataSourceFactory;
import org.apache.shardingsphere.data.pipeline.core.execute.ExecuteEngine;
-import org.apache.shardingsphere.test.it.data.pipeline.core.fixture.EmbedTestingServer;
import org.apache.shardingsphere.data.pipeline.core.ingest.channel.memory.MemoryPipelineChannelCreator;
import org.apache.shardingsphere.data.pipeline.scenario.migration.api.impl.MigrationJobAPIImpl;
import org.apache.shardingsphere.data.pipeline.scenario.migration.config.MigrationTaskConfiguration;
@@ -49,8 +48,9 @@ import org.apache.shardingsphere.mode.metadata.persist.MetaDataPersistService;
import org.apache.shardingsphere.mode.repository.cluster.ClusterPersistRepository;
import org.apache.shardingsphere.mode.repository.cluster.ClusterPersistRepositoryConfiguration;
import org.apache.shardingsphere.mode.repository.cluster.ClusterPersistRepositoryFactory;
+import org.apache.shardingsphere.test.it.data.pipeline.core.fixture.EmbedTestingServer;
+import org.mockito.internal.util.reflection.FieldReader;
-import java.lang.reflect.Field;
import java.sql.Types;
import java.util.Arrays;
import java.util.Collections;
@@ -111,11 +111,9 @@ public final class PipelineContextUtil {
PipelineContext.initContextManager(new ContextManager(metaDataContexts, contextManager.getInstanceContext()));
}
- @SneakyThrows(ReflectiveOperationException.class)
+ @SneakyThrows(NoSuchFieldException.class)
private static ContextManager getContextManager(final ShardingSphereDataSource dataSource) {
- Field field = ShardingSphereDataSource.class.getDeclaredField("contextManager");
- field.setAccessible(true);
- return (ContextManager) field.get(dataSource);
+ return (ContextManager) new FieldReader(dataSource, ShardingSphereDataSource.class.getDeclaredField("contextManager")).read();
}
@SneakyThrows(ConcurrentException.class)