因此,我尝试对我的“类似REST的”API的服务层进行单元测试(类似REST的是因为我没有使用Springboot或任何其他框架,而是尝试从头开始编写...)。我需要这个服务(-〉cut)的模拟存储库尝试连接到数据库。存储库继承自Hibernate控制器,它当然有一个SessionFactory和一个用于任何连接的Session,但是我想,通过模拟对象,我不必担心这个问题,只需重新定义它的方法的行为。
我尝试使用@Mock注解和Mockito.mock()方法。
下面是存储库、Hibernate控制器和测试的一些示例:储存库:
public class ArtikelRepository extends HibernateController implements Serializable {}
休眠控制器:
public class HibernateController {
private static SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
private static Session session = sessionFactory.openSession();
public static void deleteById(Object id, Class deleteClass) {
session.beginTransaction();
session.delete(session.find(deleteClass, id));
session.getTransaction().commit();
}
...
}
测试项目:
@ExtendWith(MockitoExtension.class)
class ArtikelServiceUnittest {
ArtikelRepository artikelRepository = Mockito.mock(ArtikelRepository.class);
ArtikelService cut = new ArtikelService(artikelRepository);
ArtikelEntity givenArtikelEntity = new ArtikelEntity(1, "Testartikel", "Test", 1, 1.00);
@Test
void shouldReturnAListWithTheGivenEntityAsDto() {
// given
List givenList = new ArrayList() {{
add(givenArtikelEntity.toArtikelDto());
}};
when(artikelRepository.getAll("ArtikelEntity")).thenReturn(givenList);
// when
List result = cut.getAllArtikel();
// then
List expected = givenList;
assertEquals(expected, result);
}
}
以及错误堆栈跟踪:
Sep 29, 2022 2:32:32 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate ORM core version 5.5.4.Final
Sep 29, 2022 2:32:32 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
Sep 29, 2022 2:32:32 PM org.hibernate.c3p0.internal.C3P0ConnectionProvider configure
INFO: HHH010002: C3P0 using driver: com.mysql.cj.jdbc.Driver at URL: jdbc:mysql://localhost:3306/cmp_sql
Sep 29, 2022 2:32:32 PM org.hibernate.c3p0.internal.C3P0ConnectionProvider configure
INFO: HHH10001001: Connection properties: {password=****, user=root}
Sep 29, 2022 2:32:32 PM org.hibernate.c3p0.internal.C3P0ConnectionProvider configure
INFO: HHH10001003: Autocommit mode: false
Sep 29, 2022 2:32:32 PM com.mchange.v2.log.MLog
INFORMATION: MLog clients using java 1.4+ standard logging.
Sep 29, 2022 2:32:32 PM com.mchange.v2.c3p0.C3P0Registry
INFORMATION: Initializing c3p0-0.9.5.5 [built 11-December-2019 22:18:33 -0800; debug? true; trace: 10]
Sep 29, 2022 2:32:32 PM org.hibernate.c3p0.internal.C3P0ConnectionProvider configure
INFO: HHH10001007: JDBC isolation level: <unknown>
Sep 29, 2022 2:32:32 PM com.mchange.v2.c3p0.impl.AbstractPoolBackedDataSource
INFORMATION: Initializing c3p0 pool... com.mchange.v2.c3p0.PoolBackedDataSource@d3ec91c3 [ connectionPoolDataSource -> com.mchange.v2.c3p0.WrapperConnectionPoolDataSource@dbc22131 [ acquireIncrement -> 3, acquireRetryAttempts -> 30, acquireRetryDelay -> 1000, autoCommitOnClose -> false, automaticTestTable -> null, breakAfterAcquireFailure -> false, checkoutTimeout -> 0, connectionCustomizerClassName -> null, connectionTesterClassName -> com.mchange.v2.c3p0.impl.DefaultConnectionTester, contextClassLoaderSource -> caller, debugUnreturnedConnectionStackTraces -> false, factoryClassLocation -> null, forceIgnoreUnresolvedTransactions -> false, forceSynchronousCheckins -> false, identityToken -> 1hge2m2ar122sm961ef2fy9|61af1510, idleConnectionTestPeriod -> 0, initialPoolSize -> 3, maxAdministrativeTaskTime -> 0, maxConnectionAge -> 0, maxIdleTime -> 0, maxIdleTimeExcessConnections -> 0, maxPoolSize -> 15, maxStatements -> 0, maxStatementsPerConnection -> 0, minPoolSize -> 3, nestedDataSource -> com.mchange.v2.c3p0.DriverManagerDataSource@59aa486e [ description -> null, driverClass -> null, factoryClassLocation -> null, forceUseNamedDriverClass -> false, identityToken -> 1hge2m2ar122sm961ef2fy9|363a3d15, jdbcUrl -> jdbc:mysql://localhost:3306/cmp_sql, properties -> {password=******, user=******} ], preferredTestQuery -> null, privilegeSpawnedThreads -> false, propertyCycle -> 0, statementCacheNumDeferredCloseThreads -> 0, testConnectionOnCheckin -> false, testConnectionOnCheckout -> false, unreturnedConnectionTimeout -> 0, usesTraditionalReflectiveProxies -> false; userOverrides: {} ], dataSourceName -> null, extensions -> {}, factoryClassLocation -> null, identityToken -> 1hge2m2ar122sm961ef2fy9|45e1aa48, numHelperThreads -> 3 ]
Sep 29, 2022 2:33:03 PM com.mchange.v2.resourcepool.BasicResourcePool
WARNUNG: com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@1a9d92ed -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception:
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at com.mysql.cj.jdbc.exceptions.SQLError.createCommunicationsException(SQLError.java:174)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:64)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:828)
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:448)
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:241)
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:198)
at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:175)
at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:220)
at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:206)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:203)
at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1176)
at com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1163)
at com.mchange.v2.resourcepool.BasicResourcePool.access$700(BasicResourcePool.java:44)
at com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1908)
at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:696)
Caused by: com.mysql.cj.exceptions.CJCommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
at java.base/jdk.internal.reflect.DirectConstructorHandleAccessor.newInstance(DirectConstructorHandleAccessor.java:67)
at java.base/java.lang.reflect.Constructor.newInstanceWithCaller(Constructor.java:499)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:483)
at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:61)
at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:105)
at com.mysql.cj.exceptions.ExceptionFactory.createException(ExceptionFactory.java:151)
at com.mysql.cj.exceptions.ExceptionFactory.createCommunicationsException(ExceptionFactory.java:167)
at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:89)
at com.mysql.cj.NativeSession.connect(NativeSession.java:120)
at com.mysql.cj.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:948)
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:818)
... 12 more
Caused by: java.net.ConnectException: Connection refused: connect
at java.base/sun.nio.ch.Net.connect0(Native Method)
at java.base/sun.nio.ch.Net.connect(Net.java:579)
at java.base/sun.nio.ch.Net.connect(Net.java:568)
at java.base/sun.nio.ch.NioSocketImpl.connect(NioSocketImpl.java:585)
at java.base/java.net.SocksSocketImpl.connect(SocksSocketImpl.java:327)
at java.base/java.net.Socket.connect(Socket.java:633)
at com.mysql.cj.protocol.StandardSocketFactory.connect(StandardSocketFactory.java:153)
at com.mysql.cj.protocol.a.NativeSocketConnection.connect(NativeSocketConnection.java:63)
... 15 more
Sep 29, 2022 2:33:03 PM com.mchange.v2.resourcepool.BasicResourcePool
WARNUNG: com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask@44c22528 -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception:
com.mysql.cj.jdbc.exceptions.CommunicationsException: Communications link failure
Process finished with exit code -1
也许有什么想法做什么/我错过了什么或解决办法的Hibernate控制器连接?
1条答案
按热度按时间kuuvgm7e1#
它正在尝试连接,因为sessionFactory和session是静态的,将在加载类时初始化。要避免这种情况,请将它们更改为示例变量