Reputation: 3
So I'm trying to unittest the servicelayer of my "RESTful-like" API (RESTful-like because I'm not using Springboot or any other framework and instead try to code it from scratch...). The big problem here: the mocked repository, which I need for the service (-> cut), tries to connect to the database. The repository inherits from a HibernateController which of course has a SessionFactory and a Session for any connections but I thought, with mocking the object, I wouldn't have to worry about that and can just re-define the behaviour of its methods.
I tried using the @Mock annotation as well as the Mockito.mock() method.
Here are some samples of the repository, HibernateController and the test: Repository:
public class ArtikelRepository extends HibernateController implements Serializable {}
HibernateController:
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();
}
...
}
Test:
@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);
}
}
And the error stacktrace:
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
Maybe any ideas what to do/what I'm missing or workarounds for the HibernateController-connection?
Upvotes: 0
Views: 471
Reputation: 1452
Its attempting to connect because sessionFactory and session are static and will be initialised when the class is loaded. To avoid this change them to instance variables
public class HibernateController {
private final SessionFactory sessionFactory;
private final Session session;
public HibernateController() {
sessionFactory = HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
}
Upvotes: 0